38Implement Promise.race()
mediumAbout 35 minutesCodingpromisesasyncpolyfills
Problem
Implement promiseRace(iterable) without using Promise.race. It returns a promise that settles the same way as the first item to settle: it fulfils with that value or rejects with that reason.
const result = await promiseRace([
fetch("/api/search?q=js"),
new Promise((_, reject) => setTimeout(() => reject(new Error("Timed out")), 3000)),
]);Requirements
- Fulfilment and rejection both count: whichever comes first wins.
- Plain values count as already settled, so
promiseRace([slowPromise, 42])fulfils with42. - With equal timing, the earlier item in the input wins.
- An empty input returns a promise that never settles, like the built-in.
- Accept any iterable.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Video walkthrough
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
Create new Promise((resolve, reject) => …) so the caller always gets a promise.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 4 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.