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

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čí
~ 6 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
~ 6 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 Schulzinstructor
~ 6 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
~ 4 years 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 Schulzinstructor
~ 4 years 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
~ 4 years ago

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