How would you implement Promise.race from scratch? | Promise Polyfills | JavaScript Interview Questions
@Yomesh Gupta

JavaScriptBeginner
708
Do you see value in our efforts?

Devtools Tech is a free platform for Frontend Engineers. It takes a lot of time, effort, and finanical resources to keep the platform running. If you see any value in our work and would like to support us then you can do using the following options.

InternationalDomestic

You have to implement a function called race that takes an array of promises as input. It should return a promise that fulfills or rejects as soon as one of the promises in the input array fulfills or rejects, with the value or reason from that promise.

// Syntax
Promise.race(iterable);
// Example 1

const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then((value) => {
  console.log(value);
  // Both resolve, but promise2 is faster
});
// expected output: "two"
// Example 2

const promise1 = new Promise((resolve, reject) => {
  setTimeout(reject, 100, 'one');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'two');
});

Promise.race([promise1, promise2]).then((value) => {
  console.log(value);
}).catch((err) => {
  console.log(err);
  // promise1 is rejected first. Hence, it should output "one" 
});

Loading IDE...