Wait for the Fastest JavaScript Promise to Settle with Promise.race()

Marius Schulz
InstructorMarius Schulz

Share this video with your friends

Send Tweet

The Promise.race() method accepts an array (or any other iterable) of promises as a parameter. It returns a Promise object that is fulfilled or rejected once the first input promise is fulfilled or rejected:

  • As soon as any input promise is fulfilled, the returned Promise object is fulfilled with that value.
  • As soon as any input promise is rejected, the returned Promise object is rejected with that reason.

Promise.race() can be used to race multiple promises against each other and find the first promise to settle.

Daniel Krejčí
Daniel Krejčí
~ 2 years ago

I am curious. Do you know about any actual use cases for Promise.race? I had no need to use that ever.

Ian Jones
Ian Jones
~ 2 years ago

I am curious. Do you know about any actual use cases for Promise.race? I had no need to use that ever.

A common use case for racing promises is to create a time out on the client. You can send a request and race that request with a timeout of whatever length you give it, passing Promise.reject to the timeout handler.

Marius Schulz
Marius Schulzinstructor
~ 2 years ago

@Daniel: I've almost never used Promise.race() either, but this course wouldn't have been complete without it.

As Ian and I mentioned, racing a promise against a timeout promise is a possible use case. Another scenario might be fetching the same information from two different sources and only waiting for the faster response.

Erkan Buelbuel
Erkan Buelbuel
~ 8 months ago

I get an error message: TypeError: Promise.race(...).finally is not a function

function resolveAfter(ms, value) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(value);
    }, ms);
  });
}

function timeout(ms, measuringPromise) {
  let timeoutID;
  const timeoutPromise = new Promise((_, reject) => {
    timeoutID = setTimeout(() => {
      reject(Error(`Timed out after ${ms}ms`));
    }, ms);
  });

  return Promise.race([somePromise, timeoutPromise]).finally(() => {
    clearTimeout(timeoutID);
  });
}

const somePromise = resolveAfter(1000, 'Some Content');

timeout(2000, somePromise).then(
  (value) => console.log(value),
  (err) => console.warn(error.message),
);

Node v8.17.0, MacOS Catalina v10.15.6

Marius Schulz
Marius Schulzinstructor
~ 8 months ago

@Erkan: The Promise.prototype.finally method is only supported as of Node v10.0.0 (see https://node.green/#ES2018-features-Promise-prototype-finally).

Erkan Buelbuel
Erkan Buelbuel
~ 8 months ago

thank you very much, that must have been the scotch at that time, alread got it,..