JavaScript Promise allSettled() Method
Last Updated :
10 Jan, 2024
Promise.allSettled()
method in JavaScript is used to handle multiple promises concurrently and return a single promise. This promise is fulfilled with an array of promise state descriptors, each describing the outcome of the corresponding promise in the input array. Unlike Promise.all()
, Promise.allSettled()
does not short-circuit when one of the promises is rejected; instead, it waits for all promises to settle, providing information about each one.
Syntax:
Promise.allSettled(iterable);
Parameters:
This method accepts a single parameter iterable which takes an array of promises or a normal array that contains some objects.
Return Value:
This method returns the following values:
- If the passed argument is empty, it returns a Promise that is already resolved.
- For all other cases, it returns a pending Promise, along with the status as well as the values of all promises that are passed inside it individually.
Example 1: In this example, we will use the Promise allSettled() Method
Javascript
const p1 = Promise.resolve(50);
const p2 = new Promise((resolve, reject) =>
setTimeout(reject, 100, 'geek' ));
const prm = [p1, p2];
Promise.allSettled(prm).
then((results) => results.forEach((result) =>
console.log(result.status, result.value)));
|
Output
fulfilled 50
rejected undefined
Example 2: In this example, we will use the Promise allSettled() Method
Javascript
const tOut = (t) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Completed in ${t}`)
}, t)
})
}
tOut(1000).then(result => console.log(result))
Promise.allSettled([tOut(1000), tOut(2000)]).then(result =>
console.log(result))
|
Output:
"Completed in 1000"
Array [Object { status: "fulfilled", value: "Completed in 1000" },
Object { status: "fulfilled", value: "Completed in 2000" }]
Example 3: In this example, we have displayed the exact output which is received whenever we execute multiple promises and pass them inside Promise.allSettled() method.
Javascript
let first_promise = Promise.resolve(200);
let second_promise = Promise.reject( "Rejected Promise" );
let third_promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(500), 100)
});
let result =
Promise.allSettled([first_promise, second_promise, third_promise]);
result.then((value) => console.log(value));
|
Output:
[
{ status: 'fulfilled', value: 200 },
{ status: 'rejected', reason: 'Rejected Promise' },
{ status: 'fulfilled', value: 500 }
]
Supported Browsers:
- Google Chrome 76 and above
- Edge 79 and above
- Mozilla Firefox 71 and above
- Opera 63 and above
- Safari 13 and above
- Internet Explorer not supported
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...