Skip to content

Implementation of Promise.race()

I came across an implementation of the Promise.race() method in JavaScript, which works as expected, but doesn’t make much sense to me.

const race = (...promises) =>
    new Promise((res, rej) => {
        promises.forEach(p => p.then(res).catch(rej));
});

How does the forEach loop end up assigning a specific promise‘s functions?

Answer

By definition a promise resolves / rejects only once, no matter how often you call resolve or reject. Therefore the promise you construct will resolve to whatever the first promise of the promises passed resolves.