This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
35. implement `Promise.race()`

function race(promises) {
  return new Promise((resolve, reject) => {
    for (let promise of promises) {
      promise.then(resolve).catch(reject);
    }
  });
}

Explanation:

  • race() takes an iterable of promises as an argument, and returns a new Promise instance.
  • We loop over all the promises, and attach both resolve() and reject() callbacks to them via the .then() and .catch() methods.
  • Whichever promise is fulfilled or rejected first will trigger either resolve() or reject(), which will resolve or reject the returned promise of race() instantly.