How to abort a fetch API call?
You probably faced a situation where you wonder is there a way to abort an API call before it gives back a response. For example, when you are downloading a large size video and you want to cancel the downloading process after waiting for a certain amount of time.
Well, there is a good way to handle this. JavaScript provides an interface called AbortController.
The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired.
Nothing much fancy, isn’t it?
We need to understand few basic points here though,
let controller = new AbortController();
function downloadVideo() {
// ...
fetch(url, { signal: controller.signal })
.then(function (response) {
// ...
})
.catch(function (e) {
// ...
});
}
function abortDownload() {
controller.abort();
}
Here is a working example from CodeSandbox.
- Create an instance of AbortController, which in return gives us a signal object instance.
controller.signal
- Pass this signal object to our fetch request as an option inside the request’s options object.
fetch(url, { signal: controller.signal })
- When
abort()
is called, thefetch()
promise rejects with aDOMException
namedAbortError
, so we should handle it incatch
block.
Here is working example from CodeSandbox.
Originally published at https://dev.to on May 30, 2021.