JAVASCRIPT

Managing Multiple Fetch Requests with AbortController in JavaScript

Implement a robust pattern to manage and cancel multiple concurrent Fetch API requests using AbortController, improving responsiveness and resource management.

function fetchMultipleWithCancellation(urls) {
  const controller = new AbortController();
  const signal = controller.signal;

  const fetchPromises = urls.map(url =>
    fetch(url, { signal })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status} for ${url}`);
        }
        return response.json();
      })
      .catch(error => {
        if (error.name === 'AbortError') {
          console.log(`Fetch to ${url} was aborted.`);
          return null; // Or handle aborted state specifically
        }
        console.error(`Error fetching ${url}:`, error);
        throw error;
      })
  );

  const promise = Promise.all(fetchPromises)
    .then(results => results.filter(Boolean)) // Filter out nulls from aborted requests
    .catch(error => {
      if (error.name === 'AbortError') {
        console.log('Overall operation was aborted.');
        return []; // Return empty array or specific aborted state
      }
      console.error('One or more fetches failed:', error);
      throw error;
    });

  return {
    promise,
    cancel: () => {
      console.log('Cancelling all fetches...');
      controller.abort();
    },
  };
}

// Example Usage:
const apiEndpoints = [
  'https://jsonplaceholder.typicode.com/posts/1',
  'https://jsonplaceholder.typicode.com/todos/2',
  'https://jsonplaceholder.typicode.com/users/3',
  'https://jsonplaceholder.typicode.com/comments/4', // Another endpoint
];

const { promise: fetchingPromise, cancel: cancelFetches } = fetchMultipleWithCancellation(apiEndpoints);

fetchingPromise
  .then(data => {
    if (data.length > 0) {
      console.log('All non-aborted fetches completed:', data);
    } else {
      console.log('Fetching operation completed, but no data (possibly all aborted).');
    }
  })
  .catch(err => console.error('Overall fetching error:', err));

// Simulate user cancelling after a short delay
setTimeout(() => {
  console.log('--- Simulating user cancellation ---');
  cancelFetches(); // Call the exposed cancel function
}, 50); // Cancel very quickly to ensure some are aborted
How it works: This JavaScript snippet provides a robust pattern to manage and cancel multiple concurrent API requests using the `Fetch API` and `AbortController`. The `fetchMultipleWithCancellation` function returns an object containing both a `Promise` that resolves with the aggregated results and a `cancel` function. When `cancel()` is called, the `AbortController` signals all associated `fetch` requests to abort, preventing unnecessary network activity and processing. This is particularly useful for scenarios like search auto-suggestions or complex dashboards where previous requests might become obsolete due to new user input, improving resource management and responsiveness.

Need help integrating this into your project?

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

Hire DigitalCodeLabs