How to Use Promise.allSettled in JavaScript: Syntax and Examples
Promise.allSettled to wait for all promises to finish, whether they resolve or reject. It returns a new promise that resolves with an array of objects describing each promise's outcome.Syntax
The Promise.allSettled method takes an iterable (usually an array) of promises and returns a new promise. This new promise resolves when all input promises have settled (either fulfilled or rejected). The resolved value is an array of objects, each describing the outcome of each promise.
promises: An array or iterable of promises.- Returns: A promise that resolves to an array of result objects.
- Each result object has a
statusproperty:"fulfilled"or"rejected". - If
statusis"fulfilled", the object has avalueproperty with the resolved value. - If
statusis"rejected", the object has areasonproperty with the error.
Promise.allSettled(iterableOfPromises).then(results => { // results is an array of {status, value} or {status, reason} });
Example
This example shows how Promise.allSettled waits for all promises to finish and then logs their results, including both successes and failures.
const promise1 = Promise.resolve('Success 1'); const promise2 = Promise.reject('Error 2'); const promise3 = new Promise(resolve => setTimeout(() => resolve('Success 3'), 100)); Promise.allSettled([promise1, promise2, promise3]) .then(results => { results.forEach((result, index) => { if (result.status === 'fulfilled') { console.log(`Promise ${index + 1} fulfilled with:`, result.value); } else { console.log(`Promise ${index + 1} rejected with:`, result.reason); } }); });
Common Pitfalls
One common mistake is using Promise.all when you want to handle all results regardless of failures. Promise.all rejects immediately on the first failure, while Promise.allSettled waits for all promises.
Another pitfall is not checking the status property of each result, which can cause errors if you assume all promises succeeded.
/* Wrong: Using Promise.all rejects on first error */ const p1 = Promise.resolve('OK'); const p2 = Promise.reject('Fail'); Promise.all([p1, p2]) .then(results => console.log('All succeeded:', results)) .catch(error => console.log('Promise.all rejected:', error)); /* Right: Using Promise.allSettled handles all results */ Promise.allSettled([p1, p2]) .then(results => { results.forEach(r => { if (r.status === 'fulfilled') { console.log('Fulfilled:', r.value); } else { console.log('Rejected:', r.reason); } }); });
Quick Reference
| Feature | Description |
|---|---|
| Input | An iterable (usually array) of promises |
| Output | A promise resolving to an array of result objects |
| Result Object | Has 'status' ('fulfilled' or 'rejected') |
| If fulfilled | Result object has 'value' property |
| If rejected | Result object has 'reason' property |
| Use case | Get all results without failing fast on errors |