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.

TypescriptData Fetching

Code

typescriptsnippet
34 lines
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 early throw when 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

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.