JavaScript Intermediate
What is Promise.all? Please implement Promise.all
What is Promise.all()?
Promise.all(iterable) takes an iterable of Promises and returns a new Promise:
- If all Promises fulfill, it resolves with an array of all results in the original order
- If any Promise rejects, it immediately rejects with that error (fail-fast)
Basic Usage
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3]).then(values => {
console.log(values); // [1, 2, 3]
});
// Send multiple API requests in parallel (much faster than sequential)
async function loadAll() {
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);
}
Fail-Fast Example
const p1 = Promise.resolve('success');
const p2 = Promise.reject(new Error('failed'));
const p3 = Promise.resolve('also success');
Promise.all([p1, p2, p3])
.then(values => console.log(values)) // won't execute
.catch(err => console.error(err.message)); // 'failed'
Implementing Promise.all()
function myPromiseAll(promises) {
return new Promise((resolve, reject) => {
if (!promises.length) return resolve([]);
const results = [];
let completed = 0;
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then(value => {
results[index] = value; // preserve original order
completed++;
if (completed === promises.length) {
resolve(results);
}
})
.catch(reject); // reject immediately on any failure
});
});
}
Comparison with Related Methods
| Method | Behavior |
|---|---|
Promise.all() |
Resolves when ALL fulfill; rejects immediately if any rejects |
Promise.allSettled() |
Waits for ALL to settle; returns each outcome |
Promise.any() |
Resolves when ANY fulfills; rejects only if ALL reject |
Promise.race() |
Settles with the first to complete (success or failure) |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
