This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
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()
andreject()
callbacks to them via the.then()
and.catch()
methods. - Whichever promise is fulfilled or rejected first will trigger either
resolve()
orreject()
, which will resolve or reject the returned promise ofrace()
instantly.