Promise.raceLoading saved progress…

Promise.race

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.

Signature

function promiseRace(promises) {
  // returns a new Promise that settles with the outcome
  // of the first promise in `promises` to settle.
}

Examples

// 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
});

Notes

  • First to settle wins — resolve OR reject. Whichever happens first determines the outcome of the returned promise.
  • Later settlements are ignored — once the returned promise has settled, nothing else can change it. The other input promises still run; their results are just discarded.
  • Non-promise values — wrap them with Promise.resolve so a plain 42 or 'hello' in the input array behaves like an already-resolved promise.
  • Empty inputpromiseRace([]) returns a promise that never settles. That matches the spec; you don't need to throw or special-case it.
  • Don't worry about cancelling the losing promises. There's no public cancellation API on a native Promise; the losers just resolve into the void.
Loading editor…