AbortController
Cancels an in-flight fetch (or other supporting async operation) via a shared signal, rejecting its promise with an AbortError.
const controller = new AbortController(); fetch(url, { signal: controller.signal }); controller.abort();
Purpose
AbortController provides a signal that can be passed to fetch (and other cancellation-aware
APIs) to cancel an in-flight operation on demand, via controller.abort().
Syntax
const controller = new AbortController();
fetch('/api/search?q=term', { signal: controller.signal })
.then((response) => response.json())
.catch((error) => {
if (error.name === 'AbortError') {
console.log('Cancelled β expected, not a failure.');
} else {
throw error;
}
});
controller.abort(); // cancels the fetch above
Behavior notes
controller.signalcan be reused across multiple operations if they should all cancel together β callingabort()once cancels every operation currently using that signal.- A cancelled
fetchβs promise rejects with an error whose.nameis"AbortError"β this should usually be treated as an expected outcome (the request was intentionally cancelled), not logged or surfaced as a genuine failure. AbortSignal.timeout(ms)creates a signal that aborts automatically after a delay β a convenient shortcut for a request-timeout pattern without manually wiring up asetTimeout.- Cancelling a request thatβs already completed has no effect;
abort()is safe to call even if the operation already finished.
Common mistakes
- Treating an
AbortErrorthe same as a genuine network failure in error-handling/logging code, producing noisy false-positive error reports for intentional cancellations. - Forgetting to cancel a stale request when a newer one starts (search-as-you-type, for instance), leaving a race condition where the stale response can still arrive and overwrite newer state.
Runtime notes
Standard in every current browser; available as a global in Node 15 and later.