How does Promise.any() method differs from Promise.race() method in JavaScript?


In this article, you will understand how Promise.any() method differs from Promise.race() method in JavaScript.

The Promise.any() method in javascript is one among promise concurrency methods. It is useful when the first task needs to be completed.

The Promise.race() method in javascript is one among promise concurrency methods. It is useful when the first async task need to be complete, but do not care about its eventual state (i.e. it can either succeed or fail).

Example 1

In this example, let’s look at how the Promise.any() method works

console.log("Defining three promise values: promise1, promise2 and promise3");
const promise1 = Promise.resolve(1);
const promise2 = new Promise((resolve, reject) => {
   setTimeout(resolve, 2 , 'Promise Two');
});
const promise3 = 3;

console.log("
Running Promise.any method on all the three promise values") Promise.any([promise1, promise2, promise3]).then((values) => console.log(values));

Explanation

  • Step 1 − Define three promise values namely promise1, promise2, promise3 and add values to them.

  • Step 2 − Run Promise.any() method on all the promise values.

  • Step 3 − Display the promise values as result.

Example 2

In this example, let’s look at how the Promise.race() method works

console.log("Defining three promise values: promise1, promise2 and promise3");
const promise1 = Promise.resolve(Resolving first async promise);
const promise2 = new Promise((resolve, reject) => {
   setTimeout(resolve, 2 , 'Promise Two');
});
const promise3 = 3;

console.log("
Running Promise.race method on all the three promise values") Promise.race([promise1, promise2, promise3]).then((values) => console.log(values));

Explanation

  • Step 1 − Define three promise values namely promise1, promise2, promise3 and add values to them.

  • Step 2 − Run Promise.race() method on all the promise values.

  • Step 3 − Display the promise values as result.

Updated on: 16-Feb-2023

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements