JavaScript Promise race() Method Tutorial

In this section, we will learn what the Promise race() method is and how to use it in JavaScript.

What is Promise race() Method in JavaScript?

Sometimes we want to send a request to multiple external resources like servers and only care about the first one that response quicker. In situations like this, we can create a promise for a request to each server and put all of those promises in the `race()` method.

Promise race() Method Syntax:

Promise.race(iterableObject);

Promise race() Method Parameters

The `race()` method takes an iterable object (like an array) that has a bunch of promise-objects as its elements. This method creates a promise that will mirror the first promise object inside this iterable object that reached a resolved or rejected state.

Promise race() Method return value

The return value of this method is a Promise object that mirrors the state of the first Promise object in the target iterable object that resolved first.

Example: using Promise race() method in JavaScript

const prom1 = new Promise((resolve,reject)=>{
  setTimeout(()=>{
    resolve("The first promise resolved");
  },1000);
});
const prom2 = new Promise((resolve, reject)=>{
  setTimeout(()=>{
    reject("The second promise rejected");
  },2000);
})
const prom = Promise.race([
  prom1, prom2
  ]);
prom.then(resolve=>{
  console.log(resolve);
}).catch(reject=>{
  console.log(reject);
})

Output:

The first promise resolved

Here, the `race` method took two promises named `prom1` and `prom2`. The `prom1` resolved at one second after running the program, but the `prom2` rejected at 2 seconds later.

So because the `prom1` is resolved quicker, the `race` method will mirror this promise and create a Promise object that is resolved (because the `prom1` is resolved as well).

That’s how the `resolved` handler of the Promise `prom` gets called.

Example: JavaScript Promise race() method

Now let’s refactor the program above and change the timer for the `prom2` to 1 second and the timer for the `prom1` to 2 seconds (basically, we’re changing the timers).

const prom1 = new Promise((resolve,reject)=>{
  setTimeout(()=>{
    resolve("The first promise resolved");
  },2000);
});
const prom2 = new Promise((resolve, reject)=>{
  setTimeout(()=>{
    reject("The second promise rejected");
  },1000);
})
const prom = Promise.race([
  prom1, prom2
  ]);
prom.then(resolve=>{
  console.log(resolve);
}).catch(reject=>{
  console.log(reject);
})

Output:

The second promise rejected.

As you can see, this time the second promise `prom2` won, because it settled faster than the `prom1`.

Leave a Reply