Promise Methods

·

2 min read

Promise

Promise represents the completion or failure of an asynchronous task and returns its value. A promise has three states:-

       - pending: while the promise is running
       - fulfilled: when the promise is resolved and returns a value
       - rejected: when the promise is failed

Promise Methods

Promise.all()

Promise.all() takes an iterable of promises as inputs and returns an array containing values returned by each promise. If any of the iterable promises is rejected then the Promise.all() returns as soon as the first rejected promise is encountered and returns the rejected value. An already resolved promise is returned, if the iterable is passed empty.

const promise1 = Promise.resolve(10);
const promise2 = 27;
const promise3 = Promise.resolve(4);

Promise.all([promise1, promise2, promise3]).then(data => console.log(data));  
// Output= [10, 27, 4]

Promise.allSettled()

Promise.allSettled() takes an iterable of promises as inputs and returns an array containing resolved and rejected status and value of each promise.

const promise1 = Promise.resolve(10);
const promise2 = 27;
const promise3 = Promise.reject(4);

Promise.allSettled([promise1, promise2, promise3]).then(data => console.log(data));  
// Output= [{status: "fulfilled", value: 10}, {status: "fulfilled", value: 27}, {status: "rejected", value: 4}]

It differs from Promise.all() as it returns fulfilled as well as rejected promises while Promise.all() only returns one.

Promise.all() should be used when all the iterable promises are dependent on each other. But if they are not dependent on each other, then Promise.allSettled() should be used.

Promise.any()

Promise.any() takes an iterable of promises as inputs and returns as soon as one of the promises is fulfilled with its value. If none of the promises are fulfilled then it returns Aggregate Error saying all the promises were rejected.

const promise1 = Promise.reject(10);
const promise2 = new Promise((resolve) => setTimeout(resolve, 0, 27));
const promise3 = Promise.resolve(4);

Promise.any([promise1, promise2, promise3]).then(data => console.log(data));  
// Output= 4

Promise.race()

Promise.race() takes an iterable of promises as inputs and returns as soon as one of the promises is fulfilled or rejected with its value.

const promise1 = Promise.reject(10);
const promise2 = new Promise((resolve) => setTimeout(resolve, 0, 27));
const promise3 = Promise.reject(4);

Promise.race([promise1, promise2, promise3]).then(data => console.log(data));  
// Output= 10

Promise.all() only returns the first fulfilled value while Promise.race() returns the first settled value which can be either resolved or rejected.

You can read more about Promises over here.