Implement Promise.race From Scratch in JavaScript
Implement Promise.race from scratch in JavaScript, handle the empty input that never settles, build a timeout wrapper and see why losers are not cancelled.

Promise.race(iterable) returns a promise that settles as soon as the first input settles, either way. If the first to finish fulfills, the race fulfills with that value. If the first to finish rejects, the race rejects with that reason. The implementation is the shortest of the Promise combinators, and its edge cases are the reason it is still a question: an empty input produces a promise that never settles, plain values win immediately, ties go to the input that comes first in the iteration order, and the losers keep running. This post builds promiseRace on Node.js 24, shows each of those behaviors with output, and applies it to the most common real use, a timeout around a slow call. Its siblings are Promise.all, allSettled and any.
The behavior to match
const delay = (value, ms) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (message, ms) => new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
console.log(await Promise.race([delay("slow", 30), delay("fast", 5)]));
try {
await Promise.race([delay("slow", 30), fail("quick failure", 5)]);
} catch (error) {
console.log(error.message);
}
console.log(await Promise.race([delay("late", 10), "plain value"]));fast
quick failure
plain valueThe first call returns the fastest fulfillment. The second shows that rejection counts as settling too: the quick failure ends the race, even though a successful value would have arrived later. The third shows that a plain value, which is already fulfilled, beats a pending promise, since its handler runs in the next microtask.
The implementation
function promiseRace(iterable) {
return new Promise((resolve, reject) => {
for (const item of iterable) {
Promise.resolve(item).then(resolve, reject);
}
});
}
console.log(await promiseRace([delay("slow", 30), delay("fast", 5)]));
console.log(await promiseRace([delay("late", 10), "plain value"]));
try {
await promiseRace([delay("slow", 30), fail("quick failure", 5)]);
} catch (error) {
console.log(error.message);
}fast
plain value
quick failureThat is the whole algorithm. Every input is turned into a promise, and the outer promise's resolve and reject are attached as the handlers. The first input to settle calls one of them, and the outer promise settles. Every later call is ignored, because a promise can only settle once, and that single rule is what makes the function correct without any extra state. There is no counter, no results array and no flag.
The loop uses for...of directly on the iterable, which accepts arrays, sets and generators, and works without taking a snapshot. If iterable is not iterable, for...of throws a TypeError inside the executor, which turns into a rejection of the returned promise, the same behavior as the real function.
try {
await promiseRace(undefined);
} catch (error) {
console.log(error.name);
}TypeErrorThe empty input
An empty iterable gives a promise that never settles.
const forever = promiseRace([]);
const status = await Promise.race([forever.then(() => "settled"), delay("still pending after 20 ms", 20)]);
console.log(status);still pending after 20 msThis is specified behavior, not a bug. With nothing to wait for, nothing can win. It matters because code that builds the list of promises dynamically and happens to get an empty list will hang without any error. Guard against it in your own code: check that the list is not empty before racing, or add a sentinel promise to the list that resolves to a default.
Ties and ordering
When two inputs are already settled, the one that comes first in the iteration order wins, because its then handler is attached first and handlers run in order.
const winner = await promiseRace([Promise.resolve("first"), Promise.resolve("second"), "third"]);
const failing = await promiseRace([Promise.reject(new Error("first rejects")), Promise.resolve("second")]).catch((e) => e.message);
console.log(winner, "|", failing);first | first rejectsBoth inputs in each list are ready at once, and the earlier one in the array wins. This is the reason the order of arguments to race is part of its meaning when inputs may already be settled.
The losers keep running
Promise.race does not cancel the inputs that lose. Their work goes on, and when they finish, their results are discarded.
const log = [];
const slowTask = async () => {
await delay(null, 20);
log.push("slow task finished anyway");
};
await promiseRace([delay("done", 5), slowTask()]);
log.push("race over");
await delay(null, 40);
console.log(log);[ 'race over', 'slow task finished anyway' ]The race ended at 5 ms, and the slow task completed at 20 ms. If that task was an HTTP request, it consumed bandwidth and a connection to the end. For real cancellation, pass an AbortSignal into the task and abort it when the race is decided.
async function raceWithCancel(tasks) {
const controller = new AbortController();
try {
return await promiseRace(tasks.map((task) => task(controller.signal)));
} finally {
controller.abort();
}
}
const slowAware = (signal) =>
new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve("slow"), 50);
signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(new Error("aborted"));
});
});
const fastAware = () => delay("fast", 5);
const result = await raceWithCancel([slowAware, fastAware]);
console.log(result);fastWhen the race is decided, finally aborts the signal, the slow task clears its timer and rejects. That rejection has no one waiting for it except our then(resolve, reject) handler on the outer promise, which ignores it, so there is no unhandled rejection. The design is the point to make in an interview: the race picks a winner, and cancellation is a separate job that tasks have to cooperate with.
The timeout wrapper
The most common real use of race is to put a time limit on a slow operation.
function withTimeout(promise, ms, message = "timed out") {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(message)), ms);
});
return promiseRace([promise, timeout]).finally(() => clearTimeout(timer));
}
console.log(await withTimeout(delay("in time", 5), 50));
try {
await withTimeout(delay("too slow", 100), 10, "took longer than 10 ms");
} catch (error) {
console.log(error.message);
}in time
took longer than 10 msThe wrapper creates a promise that rejects after ms, races it against the real work, and clears the timer afterward. Clearing it matters: without clearTimeout, a successful call leaves a pending timer that keeps the Node.js process alive until it fires and holds the closure in memory. The underlying operation is not stopped when the timeout wins. For fetch, AbortSignal.timeout(ms) is better because it aborts the request itself.
const signal = AbortSignal.timeout(20);
try {
await new Promise((resolve, reject) => {
signal.addEventListener("abort", () => reject(signal.reason));
setTimeout(resolve, 100);
});
} catch (error) {
console.log(error.name);
}TimeoutErrorAbortSignal.timeout creates a signal that aborts with a TimeoutError after the given time, and it is available in Node.js 17.3 and later and in current browsers.
Using race to take the first success
A frequent misuse is to use race to get the first successful result. It does not do that: the first failure ends the race too. For "first success", use Promise.any, which ignores rejections until all inputs have failed, and is the subject of implementing Promise.any.
const viaRace = await Promise.race([fail("mirror 1 down", 5), delay("mirror 2", 20)]).catch((e) => e.message);
const viaAny = await Promise.any([fail("mirror 1 down", 5), delay("mirror 2", 20)]);
console.log(viaRace, "|", viaAny);mirror 1 down | mirror 2Where race fits and where it does not
race is a good fit for a handful of situations. A timeout is the main one. Another is "whichever source answers first", for example asking a cache and a database at once and taking the faster reply, as long as both answers are equally valid. A third is waiting for one of several events, such as a user action or a shutdown signal, where each event is wrapped in a promise.
It is a poor fit for the first success, since a quick failure wins, and for collecting results, since you only get one. It is also a poor fit for a pool of workers that pick the next job as soon as one finishes. That job is done by a loop of await calls on a shared queue, and trying to do it by racing the pending tasks in a loop is a known source of bugs: each iteration re-attaches handlers to the same promises, which grows memory with the number of loops, and it is easy to lose track of which task finished.
When you do race in a loop, for example to drain a set of in-flight requests, keep the promises in a Set and remove each one when it settles. That way the set only holds the promises that are still pending, and the handlers are attached once per promise.
Tests
import test from "node:test";
import assert from "node:assert/strict";
test("promiseRace settles with the first input to settle", async () => {
assert.equal(await promiseRace([delay("a", 20), delay("b", 1)]), "b");
await assert.rejects(promiseRace([delay("a", 20), fail("x", 1)]), /x/);
});
test("promiseRace of an empty list stays pending", async () => {
const outcome = await Promise.race([promiseRace([]).then(() => "settled"), delay("pending", 10)]);
assert.equal(outcome, "pending");
});ℹ tests 2
ℹ pass 2
ℹ fail 0How to present it
State the contract: settle with the first input to settle, success or failure. Write the five-line implementation, and explain why it works without extra state: a promise settles once, so later calls to resolve and reject are no-ops. Then offer the three edge cases as things you would check: the empty input, the order for ties and the fact that losers are not cancelled. Close with the timeout wrapper and the clearTimeout detail, which shows that you have used it in production.


