JavaScript: abort()
Calling controller.abort() cancels a fetch request or other operation connected to its signal.
What you will learn
- How to pass an
AbortControllersignal - How to handle cancellation as
AbortError - How to cancel work after navigation, user action, or a timeout
Minimal example
const controller = new AbortController();
fetch("data.json", { signal: controller.signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === "AbortError") {
console.log("The request was cancelled.");
return;
}
console.error("The request failed:", error);
});
controller.abort();Pass controller.signal when starting the operation. Calling abort() later rejects the Promise with an AbortError, so cancellation can be reported separately from a network or server failure.
Important points
- One controller can control several operations that use the same signal.
- After a controller is aborted, create a new controller for a new request.
- Cancellation is useful when a request becomes irrelevant, such as after a user starts a newer search.