snippetjavascriptModeratepending
AbortController patterns — cancellable fetch, timeouts, and cleanup
Viewed 0 times
AbortControllerAbortSignalcancel fetchtimeoutsignalany
browsernodejs
Problem
Need to cancel in-flight fetch requests on component unmount, implement request timeouts, or cancel any abortable async operation cleanly.
Solution
AbortController patterns for fetch cancellation, timeouts, combining signals, and React cleanup.
Code Snippets
AbortController for fetch, timeouts, and React
// 1. Cancel fetch on cleanup
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
.then(r => r.json())
.catch(e => { if (e.name !== 'AbortError') throw e; });
// Later: controller.abort();
// 2. Fetch with timeout
async function fetchWithTimeout(url, ms = 5000) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), ms);
try {
const res = await fetch(url, { signal: controller.signal });
return await res.json();
} finally {
clearTimeout(timeout);
}
}
// 3. AbortSignal.timeout (modern)
fetch('/api/slow', { signal: AbortSignal.timeout(5000) });
// 4. React useEffect cleanup
useEffect(() => {
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
.then(r => r.json())
.then(setData)
.catch(e => { if (e.name !== 'AbortError') throw e; });
return () => controller.abort();
}, []);Revisions (0)
No revisions yet.