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

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...