Learn the concept
Promises & Async/Await
Promise.all resolves when all promises succeed (fails fast on first rejection). Promise.race resolves/rejects with the first settled promise. Promise.allSettled waits for all to settle regardless of outcome. Promise.any resolves with the first fulfilled promise (ignores rejections unless all fail).
JavaScript provides four static methods for composing multiple Promises:
Promise.all(promises)
Promise.race(promises)
Promise.allSettled(promises) (ES2020)
{status, value/reason} objectsPromise.any(promises) (ES2021)
const fetchUser = fetch('/api/user').then(r => r.json());
const fetchPosts = fetch('/api/posts').then(r => r.json());
const fetchComments = fetch('/api/comments').then(r => r.json());
// Promise.all — all must succeed
try {
const [user, posts, comments] = await Promise.all([
fetchUser, fetchPosts, fetchComments
]);
// All three succeeded
} catch (error) {
// Any one failed — don't know which succeeded
}
// Promise.allSettled — get all results
const results = await Promise.allSettled([
fetchUser, fetchPosts, fetchComments
]);
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Success:', result.value);
} else {
console.log('Failed:', result.reason);
}
});Using Promise.all to fetch multiple widget datasets in parallel for a dashboard that displays several data sources
Using Promise.allSettled to check status of multiple microservices without failing fast on a single outage
Using Promise.any to get data from the fastest responding CDN mirror, ignoring slower or failing ones
Build a dashboard that checks multiple API endpoints using Promise.allSettled and displays status for each
Build a fetch wrapper using Promise.race that rejects with a timeout error after a configurable duration