Promise.allSettled() – What Is the JavaScript Promise allSettled() Method?
Promise.allSettled() is a static method of the Promise
constructor function. It returns a new promise object after the fulfillment or rejection of all the items in the iterable value you’ve provided as its argument.
Syntax of the Promise.allSettled()
Static Method
Promise.allSettled(iterable);
- The
allSettled()
method’s iterable argument’s items can be promises, thenables, or any of JavaScript’s data types. Promise.allSettled()
will automatically pass each of its iterable argument’s items throughPromise.resolve()
. Therefore,allSettled()
will eventually resolve all its iterable argument’s values to a fully-fledged promise object.
Example of Promise.allSettled()
Returning a Fulfilled Promise
Promise.allSettled(["Orange", Promise.resolve(24), 715]);
// The invocation above will return:Promise { <state>: "fulfilled", <value>: Array(3) [ { status: "fulfilled", value: "Orange" }, { status: "fulfilled", value: 24 }, { status: "fulfilled", value: 715 }]}
The snippet above returned a new promise object after JavaScript resolved all the method’s array items.
When Does Promise.allSettled()
Return a Fulfilled Promise?
Promise.allSettled()
returns a fulfilled promise when the static method resolves all the items in its iterable argument.
Here’s an example:
const item1 = Promise.resolve(24);const item2 = 715;const item3 = new Promise((resolve, reject) => { setTimeout(() => { resolve("Orange"); }, 15000);});
Promise.allSettled([item1, item2, item3]).then((value) => { console.log(value);});
// The invocation above will first return:// Promise { <state>: "pending" }
// Then, after 15000 milliseconds (15 seconds), the invocation will return:Array(3) [ { status: "fulfilled", value: 24 }, { status: "fulfilled", value: 715 } { status: "fulfilled", value: "Orange" },]
The snippet above returned a fulfilled promise after JavaScript resolved all the array argument’s items.
When Does Promise.allSettled()
Return a Rejected Promise?
Promise.allSettled()
returns a rejected promise when the static method resolves all the items in its iterable argument.
Here’s an example:
const item1 = Promise.reject(24);const item2 = 715;const item3 = Promise.reject("Pinkmelon");const item4 = new Promise((resolve, reject) => { setTimeout(() => { resolve("Orange"); }, 15000);});
Promise.allSettled([item1, item2, item3, item4]).then((value) => { console.log(value);});
// The invocation above will first return:// Promise { <state>: "pending" }
// Then, after 15000 milliseconds (15 seconds), the invocation will return:Array(4) [ { status: "rejected", reason: 24 } { status: "fulfilled", value: 715 } { status: "rejected", reason: "Pinkmelon" }, { status: "fulfilled", value: "Orange" },]
The snippet above returned a rejected promise after JavaScript resolved all the array argument’s items.