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;
}
}
}How it works
Latest Request Wins With Abort Signals comes down to the class LatestRequestGate.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. TypeError is the guard’s signal — thrown at the branch, before any partial work happens.
What to watch for
- The guard
typeof task !== "function"short-circuits the flow with an earlythrowwhen its condition holds.
Using it
LatestRequestGate is the public entry point; everything else in the file exists to support it.
Key statements
return () => ticket === this.sequence;
if (typeof task !== "function") throw new TypeError("task must be a function");
if (controller.signal.aborted) return undefined;
Interactive Tools for This Topic
HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- What does the snippet do with malformed data?
- The code throws `TypeError` — the guard `typeof task !== "function"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.