Course contentsShow
← JavaScript
Lesson 2302 of 2,72347. Networking PrimitivesFree lesson

Aborting a Fetch Request

Pass an AbortSignal to fetch's options and call abort() to cancel the request before it completes.

Aborting a Fetch Request

You'll learn how to cancel an ongoing network request before it finishes using the AbortController's signal.

Why Cancel a Request?

Imagine you've sent a fetch request for large data, but the user navigates away or clicks a different button. Without cancellation, that request continues silently in the background, wasting bandwidth and potentially causing bugs when the response arrives for a component that no longer exists.

How It Works

You already know how to create an AbortController and access its signal. Now you'll pass that signal to fetch and trigger the abort when needed:

const controller = new AbortController();

fetch('https://api.example.com/large-data', {
  signal: controller.signal  // Pass the signal in options
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Fetch was cancelled');
    } else {
      console.error('Fetch failed:', error);
    }
  });

// Cancel the request before it completes
controller.abort();

When you call controller.abort(), fetch immediately stops the network request and throws an AbortError. Your catch block receives this error, allowing you to handle cancellation differently from network failures.

Practical Pattern

This is especially useful with user interactions:

const controller = new AbortController();

searchButton.addEventListener('click', () => {
  controller.abort(); // Cancel any previous search
  
  fetch(`/search?q=${query}`, { signal: controller.signal })
    .then(/* handle results */)
    .catch(/* handle errors */);
});

Key Takeaway: Pass an AbortSignal to fetch's options object and call abort() on the controller to immediately cancel the request, throwing an AbortError you can catch and handle gracefully.