The Promise.all() method provides one way for aggregating multiple promises into one.
This article assumes you have some basic knowledge of promises.
The Promise.all() method takes an iterable of promises as an input and returns a single promise. That promise is fulfilled once all promises in the input iterable are fulfilled. It rejects when any of the input promises reject, using that rejection as a value.
Note that Promise.all() gives its result in the same order as the input array, not in the order that the input promises fulfilled
Promise.all() will execute asynchronously, even if the input promises are all fulfilled already.
As you can see, immediately after the promise is created, it is still pending even though the input promises are fulfilled.
Promise.all() will only execute synchronously when the input iterable is empty.
Even though non-promise values are ignored by Promise.all(), the method is still asynchronous. Only for an empty iterable does it run synchronously.
Promise.all() is fail-fast, meaning it immediately rejects on the first input promise that rejects.
For a similar method that isn’t fail-fast, check out Promise.allSettled(). This method returns a promise that fulfills once all input promises have either fulfilled OR rejected, with an array of objects indicating which promises fulfilled or rejected.
Example Use Case:
Say you want to perform a large batch of asynchronous requests to a third-party API and bundle the responses. Promise.all() provides an effective solution.
Now you know how to use Promise.all()! If you haven’t already, try the method out yourself to get a better feel of how it works. Remember that all() isn’t the end all be all for doing multiple asynchronous actions at once. Alternative methods like Promise.allSettled() or the async/await keywords have different use cases and might be better suited to a particular task. Happy coding!