Promise Methods in Javascript

Introduction

A promise represents the eventual result of an asynchronous operation. Before the introduction of the promise, asynchronous actions were handled using callbacks. But that created unmanageable code, something which we call callback hell. Promise is nothing but an object on which you can attach callbacks instead of passing callbacks into a function.

doSomethingAsync(parameter, successCallback, failureCallback);

So the above can be written as

doSomethingAsync(parameter).then(successCallback, failureCallback);

And by using async/await this will become more readable.

const someAsyncFunction = async (parameter) => {
  try {
    const res = await doSomethingAsync(parameter);
    successCallback(response);
  } catch (errr) {
    failureCallback(err);
  }
};

Now let's take look at different promise methods.

Different methods of Promise

1. Promise.all()

This method takes the array of promises as an argument and returns a single promise whose resolved value will be an array of all the results of input promises. This promise will be resolved after every single promise inside the array is resolved. Also, promise will be rejected even if a single promise fails to resolve.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("I have delay");
  }, 1000);
});

const promise2 = 23;

const promise3 = Promise.resolve("Success");

Promise.all([promise1, promise2, promise3])
  .then((res) => console.log(res))
  .catch((err) => console.log(err)); 

//Will resolve after 1000ms with value ["I have delay" , 23, "Success"]

Now, Let's add a rejected promise

const promise4 = Promise.reject("ERROR");

Promise.all([promise1, promise2, promise3, promise4])
  .then((res) => console.log(res))
  .catch((err) => console.log(err));
/*Will be rejected right after encountering rejected promise with value "ERROR"*/

Promise.all() is used in cases where our code is dependent on multiple asynchronous tasks and all of them should be fulfilled before continuing with execution.

2.Promise.any()

This method also takes an array of promises as arguments but returns a single promise with the resolved value of the promise which is resolved first and if no promise is resolved then the promise gets rejected with AggregateError.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Slow");
  }, 1000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Medium");
  }, 500);
});

const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Fast");
  }, 100);
});

const promise4 = Promise.reject("ERROR");

Promise.any([promise1, promise2, promise3, promise4])
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

/*Will resolve after 100ms with value "Fast"*/

3.Promise.allSettled()

This method also takes the promises array as an argument and always resolves with an array of objects which describes the status of all the promises in the array.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Slow");
  }, 1000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Medium");
  }, 500);
});

const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Fast");
  }, 100);
});

const promise4 = Promise.reject("ERROR");

Promise.allSettled([promise1, promise2, promise3, promise4])
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

/*Will resolve after 1000ms with value
[
0: {status: 'fulfilled', value: 'Slow'}
1: {status: 'fulfilled', value: 'Medium'}
2: {status: 'fulfilled', value: 'Fast'}
3: {status: 'rejected', reason: 'ERROR'}
]*/

4. Promise.race()

This method returns the first settled value either fulfilled or rejected. Unlike Promise.any() which returns only resolved value.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Slow");
  }, 1000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Medium");
  }, 500);
});

const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Fast");
  }, 100);
});

const promise4 = Promise.reject("ERROR");

Promise.race([promise1, promise2, promise3, promise4])
  .then((res) => console.log(res))
  .catch((err) => console.log(err));
/* Will be rejected right away after promise4 is rejected with value "ERROR"*/

Thanks for reading.

Refrences

  1. Using Promises
  2. Promise.any()
  3. Promise.all()
  4. Promise.allSettled()
  5. Promise.race()