JS: Promise.race

By Xah Lee. Date: . Last updated: .
Promise.race(iterable)

iterable is a Iterable Object. Each yield should be a promise. If not, it is treated as resolved value of fulfilled promise.

returns a new promise which is settled in the same way as the first passed promise to settle.

  • Only the first settlement matters; the rest keep running but are ignored.
  • Empty iterable → the returned promise never settles.

Example

const fast = new Promise((resolve) => setTimeout(() => resolve("fast"), 100));
const slow = new Promise((resolve) => setTimeout(() => resolve("slow"), 500));
const fail = new Promise((_, reject) => setTimeout(() => reject("error"), 200));

Promise.race([fast, slow])
 .then(
  (x) => console.log("fulfilled with value:", x),
  (x) => console.log("rejected with value:", x),
 );
// fulfilled with value: fast

Promise.race([slow, fail])
 .then(
  (x) => console.log("fulfilled with value:", x),
  (x) => console.log("rejected with value:", x),
 );
// rejected with value: error