ES2020 -Promise allSettled
The 11th edition, or ECMAScript 2020, was published in June 2020. And introduce many new features and allSettled() method is one of them.
Basically promise in JS are used to handle asynchronous operations. Promise have 3 states. One is fulfilled or resolved, 2nd one is rejected or 3rd one is neither fulfilled nor rejected.
In ES6 / ES2015, Promises are implemented as inbuilt standard part of JS. all(), race(), reject() and resolve() methods are implemented. In ES2020 JavaScript introduce a new promise class i.e. promise.allSettled().
Before ES2020 promise.all() takes array of promises, halts it’s execution , thrown error and reject promise once rejected promises occurred in array of promises.
In this above example 1st promise is resolved , 2nd is rejected and 3rd is not executed.
In ES2020 promise. allSettled() returns result of all promises.
syntax: Promise.allSettled([array of promises])
It’s Return type is array of promises i.e. {status : “fulfilled/rejected”, value: “userdefined” }
Let take an example and see how promise.allSettled() works. Let’s create 3 promises , promise1 will be resolved, promise2 will be rejected and promise3 will be resolved.
The output of the above code is
[{ status : ‘fulfilled’ , value: “undefined” },
{status: ‘rejected’ , value: “error” },
{status: ‘fulfilled’, value: “undefined” }]
So let’s discuss the difference between promise.all() and promise. allSettled()
promise.all():
Input is array of promises.
Reject promise if one of the promise is rejected.
Result array length is <= input length.
Useful for multiple call for success operations.
promise.allSettled():
Input is array of promises.
Resolved all promises even though one of promise is rejected.
Result array length is equal to input length.
Useful for get status of multiple API. i.e. success/ failure operation.
This is all about javascript ES2020 promise.allSettled().
Keep Learning and Keep Growing !