Different Promise Methods

Different Promise Methods

There are various methods in Promises. These methods may seem trivial at start but I hope you will understand each one of them in this blog. Let's see how each method behaves differently with examples.

Prerequisites

This blog assumes that you are familiar with the Promise Constructor, resolve and reject methods in Javascript. Also, you should have familiarity with asynchronus JS.

Let's see each Promise method one by one.

Promise.all()

  • Promise.all() method accepts an iterable, usually an array of Promises and returns a Promise.
  • This returned Promise will resolve when all of the input's promises have been resolved, or the iterable input does not contain promises.
  • The returned Promise will be resolved into an array of the result of each Promise in the input iterable.
  • The order of elements in the result array will be same as the input Promise iterable.
  • If any of the promises is rejected, the promise returned by Promise.all() immediately rejects with that error.
  • When an empty iterable is passed, the method will return an already resolved Promise with result as empty array.

Let's look into the examples below for clear understanding

//Example 1
Promise.all([
  new Promise(resolve => setTimeout(() => resolve(1), 3000)), 
  new Promise(resolve => setTimeout(() => resolve(2), 2000)), 
  new Promise(resolve => setTimeout(() => resolve(3), 1000)) 
]).then(res => console.log(res));
//Expected Output : [1, 2, 3]
//Example 2
Promise.all([
  new Promise(resolve => setTimeout(() => resolve(1), 3000)), 
  200, 
  new Promise(resolve => setTimeout(() => resolve(3), 1000)) 
]).then(res => console.log(res));
//Expected Output : [1, 200, 3]
//Example 3
Promise.all([
  new Promise((resolve,reject) => setTimeout(() => reject(1), 3000)), 
  new Promise(resolve => setTimeout(() => resolve(2), 3000)), 
  new Promise(resolve => setTimeout(() => resolve(3), 1000)) 
]).then(res => console.log(res))
.catch(err => console.log(err));
//Expected Output : 1
//Example 4
Promise.all([]).then((res) => console.log(res));
//Expected Output : []

Promise.all() can be used where we have to download several URLs in parallel and process the content once they are all done. In other words, this method is preferred in case of dependant asynchronous tasks.

Promise.allSettled()

  • Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
  • The order of objects in the result array will be same as the input Promise iterable.
  • The resulting array has:

    • {status : 'fulfilled', value : result} for successful responses,
    • {status : 'rejected', reason : error} for errors.
  • When an empty iterable is passed, the method will return an already resolved Promise with result as empty array.
//Example 1
Promise.allSettled([
  new Promise(resolve => setTimeout(() => resolve(1), 3000)), 
  new Promise(resolve => setTimeout(() => resolve(2), 2000))
]).then(res => console.log(res));
//Expected Output :[ {status: 'fulfilled', value: 1}, {status: 'fulfilled', value: 2}]
//Example 2
Promise.allSettled([
  new Promise((resolve,reject) => setTimeout(() => reject(1), 2000)), 
  new Promise(resolve => setTimeout(() => resolve(2), 3000))])
.then(res => console.log(res))
.catch(err => console.log(err));
//Expected Output : [ {status: 'rejected', reason: 1}, {status: 'fulfilled', value: 2}]
//Example 3
Promise.allSettled([]).then((res) => console.log(res));
//Expected Output : []

Consider an example where we’d like to fetch the information about multiple users. Even if one request fails, we’re still interested in other users. In other words, this method is preferred in case of independent asynchronous tasks.

Promise.race()

  • The Promise.race() method returns a Promise that is resolved or rejected, as soon as one of the promises in an iterable, fulfills or rejects, with the value or reason from that Promise.
  • Promise.race() will resolve to the first value found in the iterable, if the iterable contains one or more non-promise value or an already settled promise.
  • When an empty iterable is passed, the method will return a promise which will be forever pending. Lets see the examples
//Example 1
Promise.race([
  new Promise(resolve => setTimeout(() => resolve(1), 3000)), 
  new Promise(resolve => setTimeout(() => resolve(2), 2000))
]).then(res => console.log(res));
//Expected Output : 2
//Example 2
Promise.race([
  new Promise((resolve,reject) => setTimeout(() => reject(1), 2000)), 
  new Promise(resolve => setTimeout(() => resolve(2), 3000))])
.then(res => console.log(res))
.catch(err => console.log(err));
//Expected Output : 1
//Example 3
Promise.race([]).then((res) => console.log(res));
//Expected Output :

In the third example, no output will be printed as the Promise will forever be in pending state, so .then() method won't be executed.

Promise.race() is similar to running race in real life, whoever comes first wins the race.

Promise.any()

  • Promise.any() method returns a Promise that is resolved as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise.
  • Promise.any() will resolve to the first value found in the iterable, if the iterable contains one or more non-promise value or an already settled promise.
  • If all of the given promises are rejected, then the returned promise is rejected with AggregateError – a special Error Object that stores all promise errors in its errors property.
  • If an empty iterable is passed, then the promise returned by this method is rejected synchronously. The rejected reason is an AggregateError object whose errors property is an empty array.

Lets see the examples

//Example 1
Promise.any([
  new Promise((resolve) => setTimeout(() => resolve(1), 2000)), 
  new Promise(resolve => setTimeout(() => resolve(2), 3000))])
.then(res => console.log(res))
//Expected Output : 1
//Example 2
Promise.any([10, new Promise((resolve) => setTimeout(() => resolve(2), 2000))
]).then((res) => console.log(res));
//Expected Output : 10
//Example 3
Promise.any([
  new Promise((resolve, reject) => setTimeout(() => reject(1), 2000)),
  new Promise((resolve, reject) => setTimeout(() => reject(2), 3000))
])
  .then((res) => console.log(res))
  .catch((err) => {
    console.log(err);
    console.log(err.errors);
  });
//Expected Output : AggregateError: All promises were rejected
// [1, 2]
//Example 4
Promise.any([])
  .then((res) => console.log(res))
  .catch((err) => {
    console.log(err);
    console.log(err.errors);
  });
//Expected Output : AggregateError: All promises were rejected
// []

Consider you are fetching data from 2 servers simultaneously to load it on the user's browser, the server which returns the fulfilled Promise first will be returned.

Summary

Promise MethodsReturn Value
all()Array of resolved values, rejects if any one fails
allSettled()Array of objects with status and value/reason for resolved and rejected Promises respectively
race()value/reason of first settled Promise
any()Value of first fulfilled Promise, throws Aggregate Error if all are rejected

That's it!! 😍 Hope this detailed explanation with examples was useful and you got the basic understanding regarding Promise methods.

References