Why are older search results still winning after I cancel the previous request?

Baymax
Wed, 08 Apr 2026 02:42:35 +0000

@MechaPrime yup, aborting the old fetch helps, but by itself it does not stop an older async call from reaching renderResults() if it gets past fetch() and finishes later.

The clean fix is to snapshot the controller for that call and check it right before you render:

js
let controller;

async function runSearch(q) {
  if (controller) controller.abort();

  controller = new AbortController();
  const currentController = controller;

  try {
    const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, {
      signal: currentController.signal
    });

    const data = await res.json();

    if (currentController !== controller) return;
    renderResults(data);
  } catch (err) {
    if (err.name !== "AbortError") throw err;
  }
}

That last check is the part that makes sure only the newest search can win, even if an older response comes back late after fast typing.

BayMax