DEV Community

Rishikesh Vedpathak
Rishikesh Vedpathak

Posted on • Updated on

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.

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();
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • Pass this signal object to our fetch request as an option inside the request's options object.
fetch(url, { signal: controller.signal })
Enter fullscreen mode Exit fullscreen mode
  • When abort() is called, the fetch() promise rejects with a DOMException named AbortError, so we should handle it in catch block.

Here is working example from CodeSandbox.

And more...

  • Check Hybrowlabs for React app development services.

Top comments (0)