To abort/cancel a JavaScript fetch() call, you need to do the following:
- Create a new
AbortControllerobject instance; - Retrieve the
AbortSignalobject instance viaAbortController.signalproperty; - Specify the
AbortSignalobject as the value for thesignaloption in thefetch(url, options)call; - Call the
AbortController.abort()method to signal an abort to the associatedfetch()call.
For example, you can implement this using async/await syntax in the following way:
const controller = new AbortController();
const signal = controller.signal; // returns instance of `AbortSignal`
const url = 'https://hub.dummyapis.com/delay?seconds=5';
setTimeout(() => {
controller.abort(); // DOMException: The user aborted a request.
}, 1000);
const response = await fetch(url, { signal });
console.log(response);
// ...
In this example, the dummy API delays the response by 5 seconds to demonstrate how the request can be aborted — as demonstrated, for example, in one second using a timeout.
You can rewrite the same example using the promises syntax in the following way:
const controller = new AbortController();
const signal = controller.signal; // returns instance of `AbortSignal`
const url = 'https://hub.dummyapis.com/delay?seconds=5';
setTimeout(() => {
controller.abort(); // DOMException: The user aborted a request.
}, 1000);
fetch(url, { signal })
.then((response) => {
console.log(response);
// ...
});