JavaScript: AbortController
AbortController lets you cancel a fetch request or other supported asynchronous operation that is no longer needed.
What you will learn
- How to create a controller and pass its
signal - How to distinguish
AbortErrorfrom other failures - How cancellation helps during navigation or a timeout
Minimal example
const controller = new AbortController();
const request = fetch("data.json", { signal: controller.signal })
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.catch(error => {
if (error.name === "AbortError") {
console.log("The request was cancelled.");
return;
}
console.error("The request failed:", error);
});
controller.abort();Calling abort() causes the request to reject with an AbortError. Keep a separate branch for cancellation so it is not reported as an unexpected server or network failure.
Important points
- Pass
controller.signalto the operation you want to control. - A controller cannot be reset after aborting; create a new one for a new request.
- Cancel requests that become irrelevant, such as a previous search after the user types again.