Promise.all: Waiting for Multiple Promises
You'll learn how to run multiple promises concurrently and wait for all of them to complete successfully.
What is Promise.all?
Promise.all is a static method that takes an array (or iterable) of promises and returns a single new promise. This new promise resolves only when all the input promises have resolved successfully. If any promise rejects, Promise.all immediately rejects with that error.
Think of it like waiting for a group of friends before starting a movie. Everyone must arrive before you can press play. If one friend cancels, the whole plan is off.
Running Promises Concurrently
When you use Promise.all, all the promises start executing at the same time (concurrently), not one after another. This is different from chaining .then() calls, which runs operations sequentially.
const promise1 = fetch('/api/user');
const promise2 = fetch('/api/posts');
const promise3 = fetch('/api/comments');
Promise.all([promise1, promise2, promise3])
.then(results => {
// results is an array: [userData, postsData, commentsData]
console.log('All requests completed!', results);
})
.catch(error => {
console.log('At least one request failed:', error);
});
The Result
When all promises succeed, Promise.all resolves with an array containing all the resolved values in the same order as the input promises. If the first promise in your array resolves last, its value is still first in the results array.
All-or-Nothing Behavior
Promise.all follows an "all-or-nothing" pattern. One rejection stops everything. The returned promise rejects immediately, even if other promises are still pending.
Key Takeaway: Use Promise.all when you need multiple async operations to complete concurrently and want to wait for all of them—it's faster than sequential chains but fails if any promise rejects.