How to Abort a JavaScript fetch() Call?

To abort/cancel a JavaScript fetch() call, you need to do the following:

  1. Create a new AbortController object instance;
  2. Retrieve the AbortSignal object instance via AbortController.signal property;
  3. Specify the AbortSignal object as the value for the signal option in the fetch(url, options) call;
  4. Call the AbortController.abort() method to signal an abort to the associated fetch() 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.