To abort/cancel a JavaScript fetch()
call, you need to do the following:
- Create a new
AbortController
object instance; - Retrieve the
AbortSignal
object instance viaAbortController.signal
property; - Specify the
AbortSignal
object as the value for thesignal
option 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);
// ...
});
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.