AniUI Academy

Implement Promise.race from scratch

mediumAsync & Promises+250 XPPractice

Racing promises is how you build timeouts, how you pick whichever of two endpoints answers first, and how you abandon work when the user navigates away. Writing it yourself makes the settle-once rule obvious.

Implement race(promises) without using Promise.race. It returns a promise that settles exactly like the first input to settle: fulfilling with its value, or rejecting with its reason. Values in the array that are not promises count as already fulfilled. Once the returned promise has settled, later settlements of the other inputs must be ignored. An empty array returns a promise that never settles.

Arguments

promisesArray<Promise | any>
An array of promises or plain values.

Returns

Promise<any> — A promise that settles with the first input to settle — fulfilling or rejecting as that input did. Never settles for an empty array.

Examples

const winner = await race([
  new Promise((resolve) => setTimeout(() => resolve("slow"), 50)),
  new Promise((resolve) => setTimeout(() => resolve("fast"), 5)),
]);
// winner === "fast"

The first to settle wins.

try {
  await race([
    new Promise((resolve) => setTimeout(() => resolve("slow"), 50)),
    Promise.reject(new Error("boom")),
  ]);
} catch (error) {
  // error.message === "boom" — the first rejection also wins
}

A rejection settles the race just like a fulfilment.

What it has to do

  • Fulfil with the value of the first input to fulfil.
  • Reject with the reason of the first input to reject.
  • Treat non-promise entries as already fulfilled values.
  • Ignore every settlement after the first.
  • Return a promise that never settles for an empty array.

Notes

  • A promise can only settle once, so subscribing every input to the same resolve/reject automatically ignores later settlements.
  • An empty input returns a promise that never settles — this mirrors native Promise.race behaviour.
Asked atMetaGoogleNetflix

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.