What is Promise.race? How to implement it?

October 6, 2022

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

What is Promise.race()?

Before implementing this JavaScript built-in method, we need to know what it is doing. According to MDN's definition, Promise.race() will

  • Receives an Iterable with multiple promises inside it, e.g. Array, Map, Set.
  • Returns whichever is first fulfilled or first rejected. In other words, it fulfills if the first promise to settle is fulfilled, or rejects if the first promise to settle is rejected

How to implement Promise.race()

Let's look at the solution code first and see if you can understand it. Don’t worry if you don’t understand the code. We will explain it line by line through comment below:

function promiseRace(promises) {
  return new Promise((resolve, reject) => {
    for (const p of promises) {
      p.then((val) => {
        resolve(val);
      }).catch((e) => {
        reject(e);
      });
    }
  });
}

Let's take a look at the explanation through the code comment:

// the input is an iterable of promises
function promiseRace(promises) {
  // returns a single Promise
  return new Promise((resolve, reject) => {
    // iterate over promises
    for (const p of promises) {
      p.then((val) => {
        // it fulfills if the first promise to settle is fulfilled
        resolve(val);
      }).catch((e) => {
        // Or rejects if the first promise to settle is rejected
        reject(e);
      });
    }
  });
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee