Error Handling in Parallel Awaits
What you'll learn: How to safely handle errors when running multiple async operations concurrently with Promise.all and await.
When you run async operations in parallel using Promise.all, any single rejection causes the entire operation to fail immediately—this is called "fail fast" behavior. Understanding how to catch and handle these errors is crucial for robust concurrent code.
The Fail Fast Problem
When you await Promise.all([...]) inside a try/catch block, if any promise rejects, the catch block immediately fires with that rejection's error. The other operations may still be running, but you won't get their results:
async function fetchMultipleUsers() {
try {
const results = await Promise.all([
fetch('/user/1').then(r => r.json()),
fetch('/user/2').then(r => r.json()), // This one fails
fetch('/user/3').then(r => r.json())
]);
console.log(results); // Never reached
} catch (error) {
console.log('Failed:', error.message);
// Only know ONE operation failed, lose the rest
}
}
When You Need All Results
If you need to know the outcome of every operation (successes and failures), use Promise.allSettled instead:
async function fetchAllUsersWithStatus() {
const results = await Promise.allSettled([
fetch('/user/1').then(r => r.json()),
fetch('/user/2').then(r => r.json()),
fetch('/user/3').then(r => r.json())
]);
const successes = results.filter(r => r.status === 'fulfilled');
const failures = results.filter(r => r.status === 'rejected');
console.log(`Got ${successes.length}, failed ${failures.length}`);
}
With allSettled, there's nothing to catch—every outcome is returned in the results array.
Key Takeaway: Use try/catch with Promise.all when any failure should stop everything; use Promise.allSettled when you need all results regardless of individual failures.