Race with Timeout

EasyPromises & Async10 min4 tests

Implement raceWithTimeout(promise, ms, fallback) that races a promise against a timeout.

Requirements

  • If promise resolves within ms milliseconds, 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)
  1. Use Promise.race to race the original promise against a timeout.
  2. The timeout is a new Promise that resolves with fallback after ms.
  3. Wrap everything in try/catch to handle promise rejections.
  4. On any error, return fallback.

Topics

  • Promises & Async

Asked at

Amazon · Netflix · Microsoft

Join Us
blur