Exercise 3: Abort Fetch (cancel request)
Problem Statement
Create a function `fetchWithAbort(url, ms)` that aborts request after ms milliseconds.
Sample Output:
await fetchWithAbort("https://api.example.com/data", 5000)
// If completes in < 5s: returns Response
// If takes > 5s: request aborted (throws error)Solution
const fetchWithAbort = async (url, ms = 5000) => {
const c = new AbortController();
const t = setTimeout(() => c.abort(), ms);
try {
const res = await fetch(url, { signal: c.signal });
return res;
} finally {
clearTimeout(t);
}
};Explanation
Overall Goal:
- Fetch request ko timeout ke saath cancel karna.
- Slow network me hanging requests prevent karna.
Line 1: Async function
const fetchWithAbort = async (url, ms = 5000) => {ms = 5000→ default 5 seconds timeout.
Line 2: AbortController
const c = new AbortController();AbortController→ request cancel karne ke liye.c.signal→ signal object jo fetch ko pass karenge.
Line 3: Timeout setup
const t = setTimeout(() => c.abort(), ms);setTimeout→msmilliseconds ke baad execute.c.abort()→ AbortController ko abort signal bhejega.t→ timer ID store (baad me clear karne ke liye).
Line 4-7: Fetch with abort signal
try { const res = await fetch(url, { signal: c.signal }); return res; }fetch(url, { signal: c.signal })→ abort signal attach.- Agar timeout ho gaya → fetch automatically cancel.
- Agar success → response return.
Line 8-10: Cleanup
finally { clearTimeout(t); }finally→ success ya fail dono cases me execute.clearTimeout(t)→ timer cancel (agar pehle complete ho gaya).
Real world:
- Slow network: hanging requests prevent.
- User experience: timeout errors show karna.
- Resource management: unnecessary requests cancel.