How to Cancel a Fetch API Request in JavaScript?

Content verified by Anycode AI
July 21, 2024

Creating an AbortController

First, create an AbortController instance. This is your controller to manage the cancellation.

const controller = new AbortController();

Getting the Signal

Next, get the signal from the controller. This signal will be hooked up to your fetch call.

const signal = controller.signal;

Using the Signal in Fetch

Now, let's use this signal in a fetch request. Imagine you're calling some API and might need to cancel that request halfway.

fetch('https://api.example.com/data', { signal })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch aborted');
    } else {
      console.error('Fetch error:', err);
    }
  });

Aborting the Request

When you need to cancel the fetch, just call the abort method on the controller.

controller.abort();

The Whole Shebang: Putting It Together

Here's the whole thing tied together:

// Step 1: Create an AbortController instance
const controller = new AbortController();

// Step 2: Get the signal from the controller
const signal = controller.signal;

// Step 3: Use the signal in the fetch request
fetch('https://jsonplaceholder.typicode.com/posts', { signal })
  .then(response => {
    // Check if the response is ok (200-299)
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log('Data:', data);
  })
  .catch(err => {
    // Step 4: Handle errors, specifically the abort error
    if (err.name === 'AbortError') {
      console.log('Fetch was aborted');
    } else {
      console.error('Fetch error:', err);
    }
  });

// The following timeout will abort the fetch request after 2 seconds
setTimeout(() => {
  controller.abort();  // This will cancel the request
}, 2000);

Explanation in a Nutshell

Initialize the Controller:

const controller = new AbortController();  // Creates the abort controller.
const signal = controller.signal;  // Gets the signal from it.

Fetch with Signal:

fetch('https://jsonplaceholder.typicode.com/posts', { signal })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch aborted');
    } else {
      console.error('Fetch error:', err);
    }
  });

Abort the Request:

setTimeout(() => {
  controller.abort();  // This will cancel the request
}, 2000);

Extra: Event Listener for Abort

Adding an event listener for the abortion event is another way to handle aborts more cleanly:

signal.addEventListener('abort', () => {
  console.log('Fetch request was aborted via event listener');
});

And that, my friends, is how you leverage the AbortController to manage fetch requests in JavaScript, cancelling them effortlessly when you need to. Enjoy coding!

Have any questions?
Our CEO and CTO are happy to
answer them personally.
Get Beta Access
Anubis Watal
CTO at Anycode
Alex Hudym
CEO at Anycode