logo

JavaScript Promise all() 메서드

그만큼 Promise.all() 메서드 실제로 Promise 객체(모든 비동기 작업을 처리하는 데 사용되는 JavaScript의 객체이기도 함)의 메서드로, Promise 배열(반복 가능)을 입력으로 사용합니다. 단일을 반환합니다. 약속하다 모든 Promise가 Iterable로 전달되어 해결되거나 Iterable에 Promise가 포함되지 않은 경우 해결됩니다. 간단한 방법으로 전달된 Promise 중 하나라도 거부되면 약속.모두() 메서드는 다른 Promise의 해결 여부에 관계없이 이미 거부된 Promise의 값을 비동기적으로 거부합니다.

통사론:



Promise.all( iterable )>

매개변수: 이 메소드는 단일 매개변수를 허용합니다. 반복 가능한 이는 배열을 취합니다. 약속 또는 일부 개체를 포함하는 일반 배열입니다.

반환 값: 단일 Promise를 반환하려면 다음과 같은 몇 가지 규칙을 따릅니다.

  • 전달된 인수가 비어 있으면 이미 존재하는 Promise를 반환합니다. 해결됨 .
  • 전달된 iterable에 약속이 없으면 해결된 약속을 반환합니다. 비동기적으로 .
  • 다른 모든 경우에는 보류 중인 Promise를 반환합니다.

Promise.all() 메소드의 이행 및 거부:



이행: 반환된 약속이 이행되었습니다.

하위 문자열 문자열 자바
  • 전달된 iterable이 비어 있으면 이 메서드는 이미 해결된 Promise를 동기적으로 반환합니다.
  • 전달된 Promise가 모두 이행되면 반환된 Promise는 비동기적으로 이행됩니다.
  • 여기서 이 특정 메서드의 성공적인 실행은 성공적으로 실행되기 위한 모든 약속에 전적으로 달려 있습니다.

배제: 전달된 Promise 중 하나라도 거부되면 이 메서드는 다른 Promise의 해결 여부에 관계없이 해당 Promise의 값을 거부합니다. 즉, Promise가 실행되지 않으면 Promise.all() 메서드는 오류를 반환하고 다른 Promise가 성공적으로 이행되었는지 여부를 고려하지 않습니다.

아래 예에서는 JavaScript Promise.all() 메서드를 보여줍니다.



예시 1: Promise.all() 메소드는 다음을 기다립니다. 이행

자바스크립트




p1 = Promise.resolve(50);> p2 = 200> p3 =>new> Promise(>function> (resolve, reject) {> >setTimeout(resolve, 100,>'geek'>);> });> Promise.all([p1, p2, p3]).then(>function> (values) {> >console.log(values);> });>

>

>

산출

[ 50, 200, 'geek' ]>

예 2: 여기서 Promise.all() 메서드는 2000ms 후에 확인되고 출력이 배열로 표시됩니다.

자바스크립트




// Simple promise that resolves> // after a given time> const tOut = (t) =>{> >return> new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(`Completed>in> ${t}`)> >}, t)> >})> }> // Resolving a normal promise> tOut(1000).then(result =>console.log(결과 +>' '>))> // Completed in 1000> // Promise.all> Promise.all([tOut(1000), tOut(2000)])> >.then(result =>console.log(결과))>

>

>

산출:

Completed in 1000 Completed in 1000, Completed in 2000>

여기, 약속.모두() method는 유지되는 약속의 순서입니다. 배열의 첫 번째 약속은 출력 배열의 첫 번째 요소로 확인되고, 두 번째 약속은 출력 배열의 두 번째 요소가 됩니다. 등등.

예시 3: 여기는 , 그만큼 약속.모두() 메소드는 모든 Promise가 해결될 때까지 기다립니다.

자바스크립트




// Simple promise that resolves after a given time> const tOut = (t) =>{> >return> new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(`Completed>in> ${t}`)> >}, t)> >})> }> // Array contains some time duration> const durations = [1000, 2000, 3000]> const promises = []>// Empty array> durations.map((duration) =>{> >// Calling the async function timeout(), so> >// at this point the async function has started> >// and enters the 'pending' state> >// pushing the pending promise to an array.> >promises.push(tOut(duration))> })> console.log(promises)> // Passing an array of pending promises to Promise.all> // Promise.all will wait till all the promises get resolves> // and then the same gets resolved.> Promise.all(promises).then(response =>console.log(응답))> // It prints after previous promises gets resolved> // ['Completed in 1000', 'Completed in 2000', 'Completed in 3000']>

>

'메이슨의 공식'
>

출력 :

[object Promise], [object Promise], [object Promise] . . . (gap between previous and last promises) . . Completed in 1000, Completed in 2000, Completed in 3000>

예시 4: 이 예에서 볼 수 있듯이 Promise 중 하나가 실패하면 나머지 모든 Promise도 실패하고 결과는 오류 형식으로 콘솔에 표시됩니다. 그 다음에 약속.모두() 메소드가 거부됩니다.

자바스크립트




// Promise that resolves after a given time> const tOut = (t) =>{> >return> new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >if> (t === 2000) {> >reject(`Rejected>in> ${t}`)> >}>else> {> >resolve(`Completed>in> ${t}`)> >}> >}, t)> >})> }> const durations = [1000, 2000, 3000]> // Array contains some time durations> const promises = []>//empty array> durations.map((duration) =>{> >promises.push(tOut(duration))> >// Pushing durations in the promises array> })> // Passing an array of pending promises to Promise.all> Promise.all(promises).then(response =>console.log(응답))> >// Promise.all cannot be resolved, as one of the> >// promises passed, got rejected.> >.>catch>(error =>console.log(`::오류:: ${error}`))> // Promise.all throws an error.>

>

>

출력 :

Error Rejected in 2000>

예-5: 이 예제에서는 서로 다른 타이머가 포함된 타이머 함수(특히 setTimeout 함수)를 사용하고 이러한 함수는 서로 다른 Promise 내에 작성되며 결과를 얻기 위해 Promise.all() 메서드 내에서 해당 Promise가 전달됩니다.

자바스크립트

char java의 문자열




let first_promise =>new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(>'Resolved First after 1 second'>);> >}, 1000);> });> let second_promise =>new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(>'Resolved First after 2 seconds'>);> >}, 2000);> });> let third_promise =>new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(>'Resolved First after 3 seconds'>);> >}, 3000);> });> try> {> >let result = Promise.all([first_promise, second_promise, third_promise]);> >result.then((data) =>console.log(데이터));> }>catch> (error) {> >console.log(error);> }> // This code is contributed by Aman Singla...>

>

>

산출:

[  'Resolved First after 1 second',  'Resolved First after 2 seconds',  'Resolved First after 3 seconds' ]>

지원되는 브라우저:

지원되는 브라우저 자바스크립트 Promise.all() 방법은 다음과 같습니다.

  • Google 크롬 32 이상
  • 엣지 12 이상
  • 파이어폭스 29 이상
  • 오페라 19 이상
  • 사파리 8 이상
  • 인터넷 익스플로러는 지원되지 않습니다