← Back to all snippets
JAVASCRIPT

Canceling Pending API Requests with AbortController

Improve user experience and optimize network usage by learning to cancel pending fetch API requests using the AbortController in JavaScript, preventing stale data.

async function fetchDataWithCancellation(url, controller) {
  try {
    const response = await fetch(url, { signal: controller.signal });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log('Fetched data:', data);
    return data;
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Fetch request was aborted.');
    } else {
      console.error('Error fetching data:', error);
      throw error;
    }
  }
}

// Usage example:
// const controller = new AbortController();
// const signal = controller.signal;

// // Make the fetch request
// fetchDataWithCancellation('https://api.example.com/data', controller)
//   .then(data => console.log('Data received:', data))
//   .catch(error => console.error('Data fetch failed or aborted:', error));

// // To cancel the request after some time (e.g., component unmounts, new search query)
// setTimeout(() => {
//   controller.abort();
//   console.log('Request aborted by user/system.');
// }, 1000);
How it works: This snippet illustrates how to implement request cancellation using `AbortController`. This is crucial for single-page applications to prevent race conditions, avoid processing stale data, or clean up network requests when a component unmounts. An `AbortController` instance provides a `signal` that can be passed to the `fetch` options. Calling `controller.abort()` will cancel the pending request, triggering an `AbortError` in the catch block, allowing for graceful handling of the cancellation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs