Implement Promise.race
MediumPromises & Async15 min4 tests
Implement your own version of Promise.race that returns a promise that resolves or rejects as soon as the first promise in the iterable settles.
Requirements
- Resolve with the value of the first promise that resolves
- Reject with the reason of the first promise that rejects
- Handle an empty iterable (should remain pending forever)
Example
const fast = new Promise(r => setTimeout(() => r('fast'), 50));
const slow = new Promise(r => setTimeout(() => r('slow'), 200));
promiseRace([fast, slow]); // resolves with 'fast'Hints (4)
- Return a new Promise.
- Iterate over all promises and attach
.then(resolve, reject)to each. - The first one to settle will call resolve or reject, and subsequent calls are ignored.
- Wrap each value with
Promise.resolve()to handle non-promise values.
Topics
- Promises & Async
Asked at
Google · Meta · Netflix
