← Daily Logs
BFE.dev 33

Implement Promise.race

MediumJun 30, 2026promiseasyncpolyfill

Whichever input settles first — resolve or reject — wins, and the rest are ignored. The single-settle rule of promises does all the bookkeeping for free.

The problem

Reimplement `Promise.race()`. It takes an iterable of promises (or plain values) and returns a promise that settles as soon as the first input settles — adopting that input's value if it resolved, or its reason if it rejected.

Only the first one to finish matters; every input after that is discarded.

The approach

I return a new promise and attach `.then`/`.catch` to every input at once. Because a promise can only settle a single time, the first `res(data)` or `rej(err)` to fire is the one that sticks — every later call is a silent no-op, so I don't need any 'have we finished?' flag.

Wrapping each input in `Promise.resolve()` means a plain value in the array is treated as an already-resolved promise and can win the race too. There's no result array and no counter here — race only ever cares about the single winner.

The solution

js
function promiseRace(arr) {
    return new Promise((res, rej) => {
        for (let i = 0; i < arr.length; i++) {
            Promise.resolve(arr[i]).then((data) => {
                res(data)
            }).catch((err) => {
                rej(err)
            })
        }
    })
};

Time O(n)Space O(1)

All entries