How to cancel fetch request in JavaScript
Cancelling a fetch
request in JavaScript can be a bit tricky because the Fetch API does not provide a built-in way to cancel requests like the older XMLHttpRequest (XHR) API did with abort()
. However, you can achieve a form of cancellation by using a combination of the AbortController
and AbortSignal
interfaces, which are part of the newer API additions (specifically the AbortController API) in modern browsers.
Here’s a step-by-step guide on how to cancel a fetch
request using AbortController
:
Create an AbortController instance:
const abortController = new AbortController(); const signal = abortController.signal;
Pass the signal to the fetch request:
fetch(url, { signal }) .then((response) => { // Process the response }) .catch((error) => { if (error.name === "AbortError") { console.log("Fetch aborted"); } else { console.error("Error fetching data:", error); } });
To cancel the request, call
abort()
on the AbortController:abortController.abort();
Example Usage:
Here’s a complete example demonstrating how to use AbortController
to cancel a fetch
request:
// Create an instance of AbortController
const abortController = new AbortController();
const signal = abortController.signal;
// Perform the fetch request with the signal
fetch("https://api.example.com/data", { signal })
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
console.log("Data received:", data);
})
.catch((error) => {
if (error.name === "AbortError") {
console.log("Fetch aborted");
} else {
console.error("Error fetching data:", error);
}
});
// To cancel the request
abortController.abort();
Explanation:
- AbortController: This controller creates an
AbortSignal
object (signal
in the example) that can be used to communicate with the fetch request. - AbortSignal: This signal is passed as an option in the
fetch
call ({ signal }
), allowing the request to be aborted. - abort(): Calling
abort()
on theAbortController
signals to the fetch operation that the request should be canceled. This triggers anAbortError
in the fetch promise chain.
Compatibility:
AbortController
andAbortSignal
are supported in modern browsers (Chrome 66+, Firefox 57+, Safari 14+, Edge 79+).- For older browsers or compatibility with Node.js, you may need to use a polyfill, such as
abortcontroller-polyfill
.
Using AbortController
provides a more graceful way to cancel fetch
requests compared to techniques like using setTimeout
or ignoring responses after they arrive, which can lead to unnecessary network usage and resource consumption.