← Back to all snippets
JAVASCRIPT

Cancel Ongoing Fetch API Requests with AbortController

Discover how to effectively cancel pending network requests using the AbortController API in JavaScript, preventing stale data, reducing unnecessary network traffic, and optimizing resource usage in web applications.

const controller = new AbortController();
const signal = controller.signal;

async function fetchDataAndCancel(url) {
  try {
    console.log('Fetching data...');
    const response = await fetch(url, { signal });
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log('Data fetched:', data);
    return data;
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Fetch aborted by user or timeout.');
    } else {
      console.error('Fetch error:', error);
    }
    throw error;
  }
}

// Usage example:
// const myPromise = fetchDataAndCancel('https://jsonplaceholder.typicode.com/posts/1');
//
// // Simulate user action or component unmount after some time
// setTimeout(() => {
//   controller.abort();
//   console.log('Request aborted!');
// }, 100);
//
// // You can also create a new controller for each request if managing multiple independent requests
// const newController = new AbortController();
// fetchDataAndCancel('https://jsonplaceholder.typicode.com/posts/2', newController.signal)
//   .catch(err => console.log(err.name)); // Catch AbortError if aborted
// setTimeout(() => newController.abort(), 50);
How it works: This snippet demonstrates how to use the JavaScript `AbortController` API to cancel ongoing `fetch` requests. An `AbortController` creates a `signal` object, which can be passed to the `fetch` options. Calling `controller.abort()` on the controller instance will signal the associated `fetch` request to terminate. This is crucial for improving user experience (e.g., when a user types rapidly into a search box, canceling previous searches) and preventing memory leaks or race conditions, especially when components unmount before a request completes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs