- Published on
JS - EcmaScript features - Promise.all vs Promise.allSettled
Promise.all() vs. Promise.allSettled()
Both Promise.all()
and Promise.allSettled()
are used to handle multiple promises simultaneously, but they have different behaviors in terms of how they handle promise rejections.
Promise.all()
- This was introduced as part of ES6
- Takes an array of promises and returns a single promise that is fulfilled when all the promises in the array are fulfilled.
- If any of the promises in the array reject,
Promise.all()
will immediately reject with the rejection value of the first promise that rejected. - If all the promises in the array are fulfilled, the returned promise will be fulfilled with an array containing the fulfillment values of all the promises, in the same order as the input array.
Example usage:
Promise.all([promise1, promise2, promise3])
.then(values => {
console.log(values); // [value1, value2, value3]
})
.catch(error => {
console.error(error);
});
Promise.allSettled()
- This was introduced as part of ES11
- Takes an array of promises and returns a single promise that is always fulfilled when all the promises in the array have settled (either fulfilled or rejected).
- The returned promise is fulfilled with an array of objects that describe the outcome of each promise in the input array.
- Each object in the array will have a status property (either "fulfilled" or "rejected") and a value or reason property depending on the status.
Example usage:
Promise.allSettled([promise1, promise2, promise3])
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log(result.value);
} else if (result.status === 'rejected') {
console.error(result.reason);
}
});
});
Summary: Use Promise.all()
when you want to wait for all promises to be fulfilled, and any rejection should cause the entire operation to fail. Use Promise.allSettled()
when you want to wait for all promises to settle, regardless of whether they are fulfilled or rejected, and handle each promise's outcome individually.