JavaScript | Promise.allSettled() Method
The Promise is a JavaScript object which can be in three states pending, fulfilled or rejected. The Promise.allSettled() method in JavaScript is used to get a promise when all inputs are settled that is either fulfilled or rejected.
It basically returns a promise that gets resolved when all other promises which are passed are either fulfilled or rejected and in output it displays the array of objects which particularly displays the status and the value of each promise individually.
Syntax:
Promise.allSettled(iterable);
Parameters: This method accept a single parameter iterable which takes an array of promises or a normal array which contains some objects.
Return Value: This method returns the following values:
- If passed argument is empty, it returns a Promise that already resolved.
- For all other cases, it returns a pending Promise, along with the status as well as the values of all promises which are passed inside it individually.
Example 1:
Javascript
<script> // Illustration of Promise.allSettled() // Method in Javascript with Example 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))); </script> |
Output:
"fulfilled" 50 "rejected" undefined
Example 2:
Javascript
<script> // Simple promise that resolves // After a given time const tOut = (t) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(`Completed in ${t}`) }, t) }) } // Resolving a normal promise tOut(1000).then(result => console.log(result)) // Completed in 1000 // Promise.allSettled Promise.allSettled([tOut(1000), tOut(2000)]).then(result => console.log(result)) </script> |
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)); // This code is contributed by Aman Singla.... |
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
Please Login to comment...