Promise.race takes a list of promises and gives you back a single promise that copies the outcome of whichever one finishes first — winner takes all, and "winning" means settling, not necessarily resolving. If the first one to settle rejects, the returned promise rejects with that same reason.
Implement promiseRace(promises). It returns a new promise that settles the moment the first input promise settles, mirroring its resolved value or its rejection reason. Slower promises that settle afterward are ignored.
function promiseRace(promises) {
// returns a new Promise that settles with the outcome
// of the first promise in `promises` to settle.
}
// Fastest resolve wins.
const a = new Promise((res) => setTimeout(() => res('a'), 30));
const b = new Promise((res) => setTimeout(() => res('b'), 10));
const c = new Promise((res) => setTimeout(() => res('c'), 50));
promiseRace([a, b, c]).then((value) => {
console.log(value); // 'b' — b settled first
});
// Fastest settle wins — even if it's a rejection.
const slow = new Promise((res) => setTimeout(() => res('ok'), 50));
const fast = new Promise((_, rej) => setTimeout(() => rej('boom'), 10));
promiseRace([slow, fast]).catch((reason) => {
console.log(reason); // 'boom' — fast rejected first
});
// Non-promise values are treated as already-resolved promises.
promiseRace([42, slow]).then((value) => {
console.log(value); // 42
});
Promise.resolve so a plain 42 or 'hello' in the input array behaves like an already-resolved promise.promiseRace([]) returns a promise that never settles. That matches the spec; you don't need to throw or special-case it.Promise; the losers just resolve into the void.