Race with Timeout
EasyPromises & Async10 min4 tests
Implement raceWithTimeout(promise, ms, fallback) that races a promise against a timeout.
Requirements
- If
promiseresolves withinmsmilliseconds, return its value. - If the timeout fires first, return
fallback. - The function should never reject — catch any errors from the promise and return
fallback.
Example
await raceWithTimeout(
new Promise(r => setTimeout(() => r('done'), 50)),
100,
'timeout'
); // 'done'
await raceWithTimeout(
new Promise(r => setTimeout(() => r('done'), 200)),
100,
'timeout'
); // 'timeout'Hints (4)
- Use Promise.race to race the original promise against a timeout.
- The timeout is a new Promise that resolves with fallback after ms.
- Wrap everything in try/catch to handle promise rejections.
- On any error, return fallback.
Topics
- Promises & Async
Asked at
Amazon · Netflix · Microsoft
