Implement Promise.race from scratch
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/rejectautomatically ignores later settlements. - An empty input returns a promise that never settles — this mirrors native
Promise.racebehaviour.
Stuck? The javascript course covers everything this challenge needs.
- 1.fulfils with the fastest value
- 2.rejects when the fastest input rejects
- 3.treats a plain value as already fulfilled
- 4.ignores a rejection that arrives after the winner
- 5.never settles for an empty array
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.