In this lesson, you will learn how to use Promise.allSettled to manage multiple asynchronous operations so that one failure doesn’t bring your entire process to a halt.
The Problem with "All-or-Nothing"
Previously, you likely used Promise.all(). It is efficient but has a strict "all-or-nothing" rule: if even a single promise fails, the entire operation rejects immediately, ignoring any other results that might have finished successfully. In a real-world system—like calling three different external APIs to gather user data—you don’t want a single timeout on one API to prevent you from showing the data you did receive from the other two.
How Promise.allSettled Saves the Day
Promise.allSettled waits for every promise to finish, regardless of whether they succeeded or failed. Instead of stopping at the first error, it returns an array of objects that describe the outcome of each operation.
Each result object will have a status of either 'fulfilled' or 'rejected'. If it’s 'fulfilled', you get a value; if it’s 'rejected', you get a reason. This allows you to implement "recovery logic," where you can gracefully ignore errors for non-critical tasks while still processing the successful ones.
Implementation Example
Imagine you are fetching data from three different services:
const services = [fetch('/user'), fetch('/settings'), fetch('/analytics')];
const results = await Promise.allSettled(services);
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Service ${index} succeeded:`, result.value);
} else {
// Graceful recovery: just log the error instead of crashing
console.error(`Service ${index} failed with:`, result.reason);
}
});
By checking the status property, you can filter out the failed attempts and build a partial response for your application. This makes your system significantly more resilient, as you are architecting your flow to handle the "messy" reality of distributed operations where partial success is often the standard, not the exception.
Key Takeaway: Use Promise.allSettled when you need to gather data from multiple sources and want to ensure the success of individual tasks is not compromised by the failure of others.