Exercise 4: Timeout Promise
Problem Statement
Function `withTimeout(promise, ms)` banao. ms ke andar resolve na ho to reject with Error("Timeout").
Sample Output:
await withTimeout(fetchAPI(), 5000)
// If API completes in < 5s: returns API result
// If API takes > 5s: throws Error("Timeout")Solution
const withTimeout = (p, ms) =>
Promise.race([
p,
new Promise((_, rej) => setTimeout(() => rej(new Error('Timeout')), ms)),
]);Explanation
Overall Goal:
- Promise ko timeout ke saath wrap karna.
- Timeout exceed ho to error throw karna.
Solution:
const withTimeout = (p, ms) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error('Timeout')), ms))]);
Part 1: Promise.race
Promise.race([...])race→ array me se pehla resolve/reject wala Promise win karta hai.- Jo pehle complete hoga, uska result use hoga.
Part 2: Real promise
p→ original promise (actual work).- Agar ye pehle complete ho → uska result return.
Part 3: Timeout promise
new Promise((_, rej) => setTimeout(() => rej(new Error('Timeout')), ms))setTimeout→msmilliseconds ke baad execute.rej(new Error('Timeout'))→ Promise reject karta hai (error throw).- Agar ye pehle complete ho → timeout error.
How it works:
withTimeout(fetchAPI(), 5000)- Agar API 5 seconds me complete → success.
- Agar API 5 seconds se zyada le → timeout error.
Real world:
- API calls: hanging requests prevent karna.
- User experience: slow operations ko timeout karna.
- Resource management: long-running tasks limit karna.