AbortController Cancelling Inflight Fetches

Cancel stale requests with AbortController so a fast typist does not let an older response overwrite the newest one.

JavascriptResilience

Code

javascriptsnippet
27 lines
let inFlight = null;

async function search(term) {
  // 新请求前先取消上一个:避免旧响应覆盖新结果
  if (inFlight) inFlight.abort();
  const controller = new AbortController();
  inFlight = controller;

  try {
    const response = await fetch('/api/search?q=' + encodeURIComponent(term), {
      signal: controller.signal,
    });
    if (!response.ok) throw new Error('search failed: ' + response.status);
    return await response.json();
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('superseded:', term);
      return null;
    }
    throw error;
  } finally {
    if (inFlight === controller) inFlight = null;
  }
}

search('rea').then((r) => console.log('first:', r));
search('react').then((r) => console.log('second:', r));

What the code does

AbortController Cancelling Inflight Fetches comes down to the function search.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Error is the guard’s signal — thrown at the branch, before any partial work happens.

Points of care

  • This is browser-side code — fetch will not resolve in Node.
  • The guard !response.ok exits the flow through throw when its condition holds.

Applying it

The entry-point signature is async function search(term)

The demo output is labeled (superseded:, first:, second:); each label names the call that printed it.

Statements that matter

return await response.json();
const response = await fetch('/api/search?q=' + encodeURIComponent(term), {
  signal: controller.signal,
});
if (!response.ok) throw new Error('search failed: ' + response.status);

Interactive Tools for This Topic

FAQ

What happens on invalid input?
The code throws `Error` — the guard `!response.ok` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `search` at load time.