← Tous les articles

JavaScript: cancelling fetch requests with AbortController

A live search that sometimes shows results for an older query is a request that should have been cancelled. AbortController fixes it cleanly.

JavaScript: cancelling fetch requests with AbortController

Key points

  • Without cancellation, a slow response can overwrite a newer one.
  • AbortController stops an in-flight fetch request.
  • Tell a deliberate AbortError apart from a real network failure.

A client once told us their product search was “showing random things”. Typing “chair” quickly, they would sometimes get the results for “ch”. Every keystroke sent a request, and the heavier “ch” response landed after the “chair” one. The page just rendered whatever arrived last. The fix is a handful of lines.

How AbortController works

Create a controller, pass its signal to fetch(), and call abort() once the request is no longer useful. The promise then rejects with an error named AbortError.

let controller;

async function search(term) {
  controller?.abort();              // cancel the previous request
  controller = new AbortController();

  try {
    const res = await fetch(`/wp-json/wts/v1/search?q=${encodeURIComponent(term)}`, {
      signal: controller.signal,
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    render(await res.json());
  } catch (err) {
    if (err.name === 'AbortError') return; // we cancelled it on purpose
    showError(err);
  }
}

Only the latest request can now reach the screen; older ones are stopped on the way.

Adding a timeout

fetch() never times out on its own, so an API that hangs leaves your spinner turning forever. Modern browsers offer AbortSignal.timeout(), and AbortSignal.any() lets you combine signals:

const signal = AbortSignal.any([
  controller.signal,
  AbortSignal.timeout(8000),
]);
const res = await fetch(url, { signal });

Note that a timeout rejects with TimeoutError, not AbortError. On our projects we use that to show “the server is taking too long” instead of a vague failure message.

Mistakes we keep seeing

  • Reusing an aborted controller: once aborted, a signal stays aborted. Create a fresh controller per request.
  • Treating cancellation as an error: skip the err.name check and users get an error banner on every keystroke.
  • Forgetting the server: aborting in the browser does not necessarily stop PHP work already under way. If each search is expensive, debounce the input as well.

Not just for fetch

The same signal can remove event listeners: addEventListener('scroll', fn, { signal }). One abort() cleans everything up, which is handy for components that open and close, such as modals or menus, and stops listeners from piling up.

In React, the natural home for this is the cleanup function of useEffect: create the controller inside the effect and return () => controller.abort(). A component that unmounts mid-request no longer tries to update state that is gone. Vue works the same way with onUnmounted.

FAQ

Does it work with axios?

Yes. Recent axios versions accept a signal option just like fetch.

Do I still need debouncing?

They solve different problems: debouncing sends fewer requests, cancellation makes sure only the latest one is displayed.

Search, filters or forms behaving oddly on your site or app? Our front-end team tracks down and fixes exactly this kind of bug.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →