gotchajavascriptMajor
Promise.all rejects on first failure, losing other results
Viewed 0 times
Promise.allSettled requires ES2020
Promise.allPromise.allSettledparallel promiseserror handlingconcurrent requests
Error Messages
Problem
Promise.all() rejects immediately when ANY promise rejects, discarding results from promises that succeeded. If you're fetching data from 5 APIs and one fails, you lose all 5 results.
Solution
Use Promise.allSettled() to get all results regardless of success/failure:
const results = await Promise.allSettled([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments'),
]);
// Each result has { status: 'fulfilled', value } or { status: 'rejected', reason }
const successes = results.filter(r => r.status === 'fulfilled').map(r => r.value);
const failures = results.filter(r => r.status === 'rejected').map(r => r.reason);
// Or use Promise.all with individual .catch
const results = await Promise.all([
fetch('/api/users').catch(e => ({ error: e })),
fetch('/api/posts').catch(e => ({ error: e })),
]);
const results = await Promise.allSettled([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments'),
]);
// Each result has { status: 'fulfilled', value } or { status: 'rejected', reason }
const successes = results.filter(r => r.status === 'fulfilled').map(r => r.value);
const failures = results.filter(r => r.status === 'rejected').map(r => r.reason);
// Or use Promise.all with individual .catch
const results = await Promise.all([
fetch('/api/users').catch(e => ({ error: e })),
fetch('/api/posts').catch(e => ({ error: e })),
]);
Why
Promise.all is designed for the 'all or nothing' case where every promise must succeed. allSettled (ES2020) handles the 'give me whatever you can' case. The individual .catch pattern works in older environments.
Gotchas
- Promise.allSettled() returns an array of result objects, not values directly
- Promise.any() resolves with the first success (opposite of all)
- Promise.race() resolves/rejects with the first settled promise
Code Snippets
Promise.all vs allSettled
// Promise.all — fails fast
try {
const [a, b, c] = await Promise.all([p1, p2, p3]);
} catch (e) {
// ONE failed — you lost a, b, c
}
// Promise.allSettled — always completes
const results = await Promise.allSettled([p1, p2, p3]);
// results[0].status === 'fulfilled' | 'rejected'Context
When running multiple async operations in parallel where partial failure is acceptable
Revisions (0)
No revisions yet.