JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)
How does Promise.allSettled() differ from Promise.all()?
Promise.allSettled() and Promise.all() both handle multiple promises, but they behave differently when promises are rejected.
Promise.all() - fails fast:
javascript
const promises = [
Promise.resolve(1),
Promise.reject('Error'),
Promise.resolve(3)
];
Promise.all(promises)
.then(results => console.log(results))
.catch(error => console.log(error)); // 'Error'
// Stops at first rejection
Promise.allSettled() - waits for all:
javascript
Promise.allSettled(promises)
.then(results => console.log(results));
/*
[
{ status: 'fulfilled', value: 1 },
{ status: 'rejected', reason: 'Error' },
{ status: 'fulfilled', value: 3 }
]
*/
Practical example - multiple API calls:
javascript
async function fetchUserData(userId) {
const endpoints = [
fetch(`/api/users/${userId}`),
fetch(`/api/users/${userId}/posts`),
fetch(`/api/users/${userId}/comments`)
];
const results = await Promise.allSettled(endpoints);
return {
profile: results[0].status === 'fulfilled'
? await results[0].value.json()
: null,
posts: results[1].status === 'fulfilled'
? await results[1].value.json()
: [],
comments: results[2].status === 'fulfilled'
? await results[2].value.json()
: []
};
}
Filtering settled results:
javascript
const results = await Promise.allSettled(promises);
const successful = results
.filter(r => r.status === 'fulfilled')
.map(r => r.value);
const failed = results
.filter(r => r.status === 'rejected')
.map(r => r.reason);
console.log(`${successful.length} succeeded, ${failed.length} failed`);
When to use each:
| Use Promise.all() when: | Use Promise.allSettled() when: |
|---|---|
| All promises must succeed | You need all results regardless of status |
| Failure should stop execution | You want to handle each result independently |
| You want to fail fast | You need a complete report |