The Promise.all() method is actually a promise that takes an array of promises(an iterable) as an input. It returns a single Promise that resolves when all of the promises passed as an iterable, which have resolved or when the iterable contains no promises. In simple way, if any of the passed-in promises reject, the Promise.all() method asynchronously rejects the value of the promise that already rejected, whether or not the other promises have resolved.
Promise.all( iterable )
Parameters: This method accepts a single parameter iterable which takes an array of promises or a normal array which contains some objects.
Return values: It follows some rules to return a single promise:
- If passed argument is empty, it returns a Promise that already resolved.
- If passed iterable contains no promises, it returns a Promise that resolved asynchronously.
- For all other cases, it returns a pending Promise.
Fulfillment and Rejection of Promise.all() Method:
Fulfillment: The returned promise is fulfilled,
- If the passed iterable is empty, then this method returns an promise synchronously which is already resolved.
- If all of the passed promises are fulfill, the returned Promises are fulfilled asynchronously.
Rejection: If any of the passed promises are rejected, then this method rejects the value of that promise, whether or not the other promises have resolved.
Example 1: Promise.all waits for fulfillment
50, 200, geek
Example 2: Here Promise.all resolves after 2000 ms and the output is shows as an array.
Completed in 1000 Completed in 1000, Completed in 2000
Here, Promise.all is the order of the maintained promises. The first promise in the array will get resolved to the first element of the output array, the second promise will be a second element in the output array and so on.
Example 3: Here the Promise.all waits till all the promises resolve.
[object Promise], [object Promise], [object Promise] . . . (gap between previous and last promises) . . Completed in 1000, Completed in 2000, Completed in 3000
Example 4: If one of the promises fails, then all the rest of the promises fail. Then Promise.all gets rejected.
Error Rejected in 2000
- Google Chrome
- Microsoft Edge
- Mozilla Firefox
- Apple Safari
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.