Promise allSettled introduction

promises is implementation of asychronous opertions. Promise in javascript are used to handle asynchoronous operations. Each promise has three states

  • fullfilled or resolve - for successfull operations
  • rejected - for failure operations
  • neither fullfilled or rejected

Before ES6 implementation, We have promises implemented in libraries like bluebird and Q. With ES6 or ES2015, Proimses are implemented inbuilt standard part of javascript core language. all(),race,reject and resolve methods are implemented with Promise class in ES6.

allSettled() method introduced in Promise class with ES2020 to javascript feature.

Let us see the following proimse.all() example before ES2020

Created three promises - proimse1 will be resolved proimse2 will be rejected. proimse3 will be resolved.

proimse.all() takes array of promises, halts its execution, thrown error,and reject promise once rejected promise occured in array of promises.

const proimse1 = new Promise((resolve, reject) => setTimeout(resolve, 500));
const proimse2 = new Promise((resolve, reject) => setTimeout(reject, 1000));
const proimse3 = new Promise((resolve, reject) => setTimeout(resolve, 2000));

Promise.all([proimse1, proimse2, proimse3])
    .then((values) => {
        console.log('values= '+values)
        })
    .catch((error)=>{
        console.log('error='+error);
        });

Output is

Promise { <pending> }
error=undefined

In the first proimse is resolved and print its Promise its value, second promise is rejcted and third proimse is not executed.

Promise.allSettled() returns result of all promises results, irrespective of rejected or fullfilled from array of promises

Syntax

Promise.allSettled([array of promises])

Return type and Input parameters

  • Input is array of promises
  • Returned type is array of promises with each promises result is { status : ‘fulfilled/rejected’, value: “userdefined” }

Let’s see an example

const proimse1 = new Promise((resolve, reject) => setTimeout(resolve, 500));
const proimse2 = new Promise((resolve, reject) => setTimeout(reject, 1000));
const proimse3 = new Promise((resolve, reject) => setTimeout(resolve, 2000));

Promise.allSettle([proimse1, proimse2, proimse3])
.then((values) => {console.log('values= '+values)})
.catch((error)=>{
  console.log('error='+error);
});

And the output is

[{ status : 'fulfilled', value: "undefined" },
{ status : 'rejected', value: "error" },
{ status : 'fulfilled', value: "undefined" }]

Difference between allSettled and all method in a promises

allSettledall
input is array of promisesinput is array of promises
Resolves all promises eventhough one of promise is rejectedReject promise if one of the promise is rejected
Result array length is equal to input lengthResult array length is less than equal to input length
Useful for get status of multiple api -sucess/failure operationsUseful for multiple calls for success operations