Implement Promise Race
JavaScript
medium
15 mins
Implement a function promiseRace that mimics the behavior of Promise.race(). It takes an array of promises (or values) and returns a promise that settles (either resolves or rejects) as soon as the first input promise settles.
Input:
- An array of promises or values
Output:
- A single promise that resolves/rejects with the result/error of the first settled promise
Example Inputs & Outputs
// Example 1: Input: [Promise.resolve(1), Promise.resolve(2)] Output: Resolves with 1 // Example 2: Input: [Promise.reject('error'), Promise.resolve(2)] Output: Rejects with 'error' // Example 3: Input: [42, Promise.resolve(10)] Output: Resolves with 42 (since 42 is a non-promise value) // Example 4: Input: [] Output: Never settles (same as native Promise.race)
Constraints & Edge Cases
- Input can contain both promises and non-promise values.
- The result should reflect the first settled item.
- If input is empty, the returned promise should never settle.
- Input may include a mix of resolved, rejected, and pending promises.
Companies:
netflix
reddit
tcs
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
