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.
π‘ Core Concepts
1. AbortController
- Creates a controller with a
.signalobject. - You call
.abort()to cancel the operation.
2. AbortSignal
- Passed to the async operation.
- Has
.abortedboolean flag and emits anabortevent.
π§ͺ Example: Cancel fetch
const 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);
π¦ Common Use Cases
| 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 |
π§ Example in Custom Code
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 :
β Cancelable Fetch with 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() }; }
π§ͺ Example:
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);
β Behavior:
- Uses
AbortControllerto terminate the underlyingfetchrequest. - If canceled,
fetchrejects withAbortError. - Unlike
makeCancelable, this actually stops the request .
β οΈ Works With:
fetch- Some APIs like
ReadableStream,Request,WebSocket(in newer specs)
Let me know if you want a generic wrapper that adds cancelation to any async operation (not just fetch).
Quick Quiz
Test your understanding with 3 quick questions
Q1What error name is thrown when a fetch request is aborted?
Q2Which property of AbortController do you pass to fetch()?
Q3What does signal.aborted return after calling abort()?