Exercise 13: Promise Timeout Wrapper

Problem Statement

Function `withTimeout(promise, ms, timeoutValue)` banao jo promise ko timeout kare with default value. Example: withTimeout(fetchAPI(), 5000, null)

Sample Output:

await withTimeout(fetchAPI(), 5000, null)
// If timeout: rejects with null

Solution

const withTimeout = (promise, ms, timeoutValue) => {
  return Promise.race([
    promise,
    delay(ms).then(() => Promise.reject(timeoutValue))
  ]);
};

Explanation

Overall Goal:

  • Promise ko timeout kare with default value.

Real world:

  • API calls: timeout handling.
  • Operations: timeout fallback.