Latest Request Wins With Abort Signals
Cancel the previous in-flight request when a newer one starts and discard stale results using sequence checks and AbortSignal.
Code
export class LatestRequestGate {
private active: AbortController | null = null;
private sequence = 0;
private begin(): () => boolean {
this.sequence += 1;
const ticket = this.sequence;
return () => ticket === this.sequence;
}
async run<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T | undefined> {
if (typeof task !== "function") throw new TypeError("task must be a function");
const controller = new AbortController();
const isCurrent = this.begin();
if (this.active) this.active.abort();
this.active = controller;
try {
const result = await task(controller.signal);
return isCurrent() ? result : undefined;
} catch (error) {
if (controller.signal.aborted) return undefined;
throw error;
} finally {
if (isCurrent()) this.active = null;
}
}
abort(): void {
if (this.active) {
this.active.abort();
this.active = null;
}
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.