Hiprup

What is the Fetch API with AbortController?

AbortController lets you cancel a fetch request that's already in progress.

  • How — create a controller, pass its signal to fetch, and call controller.abort() to cancel.

  • Result — the fetch rejects with an AbortError you can catch and ignore.

Common uses: cancel a stale search request when the user types again, or add a timeout to a slow request.

// Basic cancellation
const controller = new AbortController();

fetch('/api/data', { signal: controller.signal })
  .then(r => r.json())
  .then(data => console.log(data))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Request cancelled');
    } else {
      console.error('Fetch error:', err);
    }
  });

// Cancel after 5 seconds (timeout)
setTimeout(() => controller.abort(), 5000);

// AbortSignal.timeout (modern shorthand)
fetch('/api/data', { signal: AbortSignal.timeout(5000) });

// Search with cancellation (cancel previous on new input)
let currentController = null;

async function search(query) {
  currentController?.abort(); // Cancel previous request
  currentController = new AbortController();
  
  try {
    const res = await fetch(`/api/search?q=${query}`, {
      signal: currentController.signal
    });
    return await res.json();
  } catch (err) {
    if (err.name !== 'AbortError') throw err;
  }
}

// Type-ahead: each keystroke cancels the previous search
input.addEventListener('input', (e) => search(e.target.value));

AbortController creates a signal that can cancel fetch. controller.abort() rejects the promise with AbortError. AbortSignal.timeout is a shorthand for timeout-based cancellation.

The search example cancels previous requests when new input arrives — only the latest search result is used (no race conditions).

The search cancellation pattern (cancel previous on new input) is the most practical example. AbortSignal.timeout for simple timeouts is the modern shorthand.

Always filter AbortError in catch (it is intentional, not an error). This pattern prevents race conditions in search-as-you-type.

What is the Fetch API with AbortController? | Hiprup