Loading article...
AbortController is a built-in Web API that allows you to cancel asynchronous operations, especially ones that support an AbortSignal, like fetch, streams, or custom async tasks.
AbortController.signal object..abort() to cancel the operation.AbortSignal.aborted boolean flag and emits an abort event.fetchconst controller = new AbortController(); const signal = controller.signal; fetch('https://api.example.com/data', { signal }) .then(res => res.json()) .then(console.log) .catch(err => { if (err.name === 'AbortError') console.log('Fetch canceled'); else console.error(err); }); // Cancel after 100ms setTimeout(() => controller.abort(), 100);
| Use Case | How AbortControllerHelps |
|---|---|
fetch()cancellation | β Native support |
| Custom async tasks | β Add your own signal checks |
| Debounce, retry, race | β Combine with timeouts or control logic |
| React effects | β Cleanup async ops on unmount |
Create a wait(ms) function that supports cancellation via AbortController.
function wait(ms, signal) { return new Promise((resolve, reject) => { const timeout = setTimeout(() => resolve("done"), ms); signal?.addEventListener("abort", () => { clearTimeout(timeout); reject(new DOMException("Aborted", "AbortError")); }); }); }
Hereβs a precise, fetch-cancelable promise implementation using AbortController :
function fetchWithCancel(url, options = {}) { const controller = new AbortController(); const signal = controller.signal; const fetchPromise = fetch(url, { ...options, signal }); return { promise: fetchPromise, cancel: () => controller.abort() }; }
const { promise, cancel } = fetchWithCancel('https://jsonplaceholder.typicode.com/posts/1'); promise .then(res => res.json()) .then(data => console.log('Fetched:', data)) .catch(err => { if (err.name === 'AbortError') { console.log('Fetch canceled'); } else { console.error('Error:', err); } }); // Cancel after 100ms setTimeout(cancel, 100);
AbortController to terminate the underlying fetch request.fetch rejects with AbortError.makeCancelable, this actually stops the request .fetchReadableStream, Request, WebSocket (in newer specs)Let me know if you want a generic wrapper that adds cancelation to any async operation (not just fetch).
Test your understanding with 3 quick questions