Problem Statement
What does Promise.all() do?
Explanation
Promise all takes an array of promises and returns a single promise.
It waits for all promises to resolve successfully. If all succeed, it returns an array of all results.
If any promise rejects, Promise all immediately rejects with that error.
Use Promise all when you need all operations to complete and the order matters.
It runs promises in parallel, not sequentially, making it faster than awaiting promises one by one.
Code Solution
SolutionRead Only
// Promise.all() - all must succeed
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
Promise.all([promise1, promise2, promise3])
.then(results => {
console.log(results); // [1, 2, 3]
});
// If any fails, all fails
const p1 = Promise.resolve(1);
const p2 = Promise.reject('Error!');
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3])
.then(results => console.log(results))
.catch(error => console.log(error)); // 'Error!'
// Practical example - fetching multiple APIs
async function getAllData() {
try {
const [users, posts, comments] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
fetch('/api/comments').then(r => r.json())
]);
console.log({users, posts, comments});
} catch (error) {
console.log('One of the requests failed:', error);
}
}
// Promise.race() - first to finish wins
Promise.race([promise1, promise2, promise3])
.then(result => console.log(result)); // 1 (first to resolve)
// Promise.allSettled() - wait for all, get all results
Promise.allSettled([p1, p2, p3])
.then(results => console.log(results));
// [{status: 'fulfilled', value: 1},
// {status: 'rejected', reason: 'Error!'},
// {status: 'fulfilled', value: 3}]
// Promise.any() - first successful promise
Promise.any([p2, p1, p3])
.then(result => console.log(result)); // 1 (first fulfilled)