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.
The basic syntax of AbortController would look like this,
let controller = new AbortController();
function downloadVideo() {
// ...
fetch(url, { signal: controller.signal })
.then(function (response) {
// ...
})
.catch(function (e) {
// ...
});
}
function abortDownload() {
controller.abort();
}
Nothing much fancy, isn't it?
We need to understand few basic points here though,
- 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.
And more...
- Check Hybrowlabs for React app development services.
Top comments (0)