Summary: in this tutorial, you’ll learn about the Promise.allSettled() method to compose promises.
Introduction to the Promise.allSettled() method
ES2020 introduced the Promise.allSettled() method that accepts a list of Promises and returns a new promise that resolves after all the input promises have settled, either resolved or rejected.
The following shows the syntax of the Promise.allSettled() method:
Promise.allSettled(iterable);Code language: JavaScript (javascript)The iterable contains the promises. The Promise.allSettled() returns a pending promise that will be asynchronously fulfilled once every input promise has settled.
The Promise.allSettled() method returns a promise that resolves to an array of objects that each describes the result of the input promise.
Each object has two properties: status and value (or reason).
- The
statuscan be eitherfulfilledorrejected. - The
valueif case the promise is fulfilled orreason) if the promise is rejected.
The following diagram illustrates how the Promise.allSettled() method works:
In this diagram:
- The
promise1rejects to theerroratt1. - The
promise2resolves to avalueatt2. - The
Promise.allSettled()method resolves to an array containing objects that describe the statuses and outcomes of thepromise1andpromise2.
JavaScript Promise.allSettled() example
The following example uses the Promise.allSettled() to wait for all the input promises to settle:
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The first promise has resolved');
resolve(10);
}, 1 * 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The second promise has rejected');
reject(20);
}, 2 * 1000);
});
Promise.allSettled([p1, p2])
.then((result) => {
console.log(result);
});
Code language: JavaScript (javascript)Output: