DEV Community

Rishikesh Vedpathak
Rishikesh Vedpathak

Posted on • Edited on

7 3

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series