AbortController Supersedes Stale Async Calls
Abort the previous request the moment a newer one starts and drop superseded results, so a slow response can never overwrite the newest answer.
Code
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function search(term: string, signal: AbortSignal): Promise<string[]> {
await sleep(60); // 模拟一次 60ms 的查询
// 真实实现里 fetch 接同一个 signal,取消由浏览器一并完成
signal.throwIfAborted(); // 已被更新的调用取代:抛 AbortError
return [`${term}-1`, `${term}-2`];
}
// 任意时刻只保留最新一次调用
let pending: AbortController | null = null;
async function latestSearch(term: string): Promise<string[]> {
pending?.abort(); // 取消上一次还没完成的调用
pending = new AbortController();
const { signal } = pending;
try {
return await search(term, signal);
} catch (error) {
if (signal.aborted) {
console.log('superseded:', term);
return [];
}
throw error;
}
}
// 连续发起而不等待:旧调用被立即取代
const first = latestSearch('orders');
const second = latestSearch('users');
const final = await latestSearch('invoices');
console.log('first resolved to:', await first);
console.log('second resolved to:', await second);
console.log('final results:', final);Output
Captured from a sandboxed run of this snippet in the build pipeline.
superseded: orders
superseded: users
first resolved to: []
second resolved to: []
final results: [ 'invoices-1', 'invoices-2' ]Abort on every new call
latestSearch starts by aborting the previous controller (pending?.abort()), then installs a fresh one. The 60ms search checks signal.throwIfAborted() after its sleep, so a superseded call raises instead of returning data.
Superseded results resolve empty
Three calls are issued without waiting: first and second both hit the abort path and print superseded: with their term before resolving to []. Only the invoices search survives to print final results: [invoices-1, invoices-2].
Why throwIfAborted
A real fetch would take the same signal; the explicit throwIfAborted marks the exact point where stale work refuses to continue, keeping the newest answer authoritative.
Interactive Tools for This Topic
FAQ
- Why resolve the superseded call to an empty array instead of throwing to the caller?
- The abort is an expected race between rapid calls, not a failure; the catch branch checks signal.aborted and returns [] so the UI treats staleness as a no-op.
- Where exactly does the stale search stop?
- At signal.throwIfAborted() right after the simulated 60ms wait — the earliest point the call can notice it was superseded.
Report a problem with this exampleOpens a pre-filled issue on GitHub.