AbortController Cancelling Inflight Fetches
Cancel stale requests with AbortController so a fast typist does not let an older response overwrite the newest one.
Code
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 —
fetchwill not resolve in Node. - The guard
!response.okexits the flow throughthrowwhen 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
cURL to fetch ConverterTranslate a curl command into equivalent JavaScript fetch() code, handling the request method, headers, JSON or raw body, and basic auth.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.