Middle+
What is the difference between Promise.all and Promise.allSettled?
sobes.tech AI
Answer from AI
Promise.all and Promise.allSettled are methods for working with multiple promises, but they differ in behavior when errors occur.
-
Promise.all takes an array of promises and returns a new promise that:
- Resolves when all promises are successfully completed, with an array of results.
- Rejects immediately if at least one promise is rejected (error), returning that promise's error.
-
Promise.allSettled takes an array of promises and returns a promise that:
- Always resolves when all promises are settled, regardless of their outcome.
- Returns an array of objects with the status of each promise (
fulfilledorrejected) and the corresponding value or reason.
Example:
const p1 = Promise.resolve(1);
const p2 = Promise.reject('error');
Promise.all([p1, p2])
.then(results => console.log(results))
.catch(error => console.log('Promise.all error:', error));
Promise.allSettled([p1, p2])
.then(results => console.log('Promise.allSettled results:', results));
Output:
Promise.all error: error
Promise.allSettled results: [
{ status: 'fulfilled', value: 1 },
{ status: 'rejected', reason: 'error' }
]
Thus, Promise.allSettled is useful when you need to wait for all promises to settle and handle their results regardless of errors.