Master JavaScript Asynchronous Programming with Promise.allSettled()
The Promise.allSettled() method is a powerful tool for handling multiple promises in JavaScript. It returns a single Promise that resolves with an array of objects, each representing the outcome of a promise in the input array.
Each outcome object contains a status property, which is either 'fulfilled' or 'rejected'.
- If the status is 'fulfilled', the object will also contain a value property with the resolved value.
- If the status is 'rejected', the object will contain a reason property with the error (typically the value passed to reject).
Key Difference: Promise.allSettled() vs. Promise.all()
Unlike Promise.all(), which immediately rejects if any promise in the iterable is rejected, Promise.allSettled() never short-circuits. It waits for all promises to settle (either fulfill or reject), making it ideal for use cases where you need to know the result of every asynchronous operation, regardless of individual failures. This provides a more robust way for error handling in async/await and promise chains.
When to use Promise.allSettled() in JavaScript?
Use it whenever you need to process the results of multiple independent asynchronous operations and you don't want a single failure to prevent you from handling the others. Common scenarios include making multiple API calls or database queries where individual failures are non-critical.
The following example demonstrates how to use Promise.allSettled() to handle a mix of successful and failed promises.
// Example: Handling multiple API calls or asynchronous tasks
const p1 = new Promise((resolve, reject) => {
setTimeout(resolve, 200, "Data for User 1"); // Simulates a successful API call
});
const p2 = new Promise((resolve, reject) => {
setTimeout(resolve, 200, "Data for User 2"); // Simulates another successful call
});
const p3 = new Promise((resolve, reject) => {
setTimeout(reject, 200, "User 3 not found"); // Simulates a failed API call (e.g., 404)
});
const p4 = new Promise((resolve, reject) => {
setTimeout(reject, 200, "Server error for User 4"); // Simulates a server error (e.g., 500)
});
// Execute all promises and handle results with allSettled
Promise.allSettled([p1, p2, p3, p4])
.then(results => {
console.log("All operations settled:");
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Promise ${index + 1}: Success -`, result.value);
} else {
console.log(`Promise ${index + 1}: Failed -`, result.reason);
}
});
});
// ** CONSOLE OUTPUT **
// All operations settled:
// Promise 1: Success - Data for User 1
// Promise 2: Success - Data for User 2
// Promise 3: Failed - User 3 not found
// Promise 4: Failed - Server error for User 4