Take Latest (Abort Previous Requests)

intermediate
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement takeLatest(fn) that wraps an async function and guarantees only the most recent call can resolve. Each new call aborts the previous one via AbortController, and stale results must not update state. This prevents out-of-order responses in search-as-you-type, autocomplete, and live filtering. Concepts: async, cancellation, race control.

Arguments

  • fn: (signal: AbortSignal, ...args: any[]) => Promise<T> — Async worker to run. It receives an AbortSignal as the first argument, followed by your call arguments.

Returns

(...args: any[]) => Promise<T> — A wrapped function that aborts the previous call and resolves only the latest result.

Solution idea

Keep at most one AbortController for the currently in-flight call. When a new call starts, abort that previous in-flight controller and increment a call id. When a promise settles, only resolve if its id matches the latest; otherwise reject with an AbortError. In an identity-guarded finally block, clear the stored controller only if it still belongs to that call. Completed calls are therefore not aborted later, and a stale completion cannot erase a newer in-flight controller.

Examples
const searchLatest = takeLatest((signal, q) =>
  fetch(`/api/search?q=${q}`, { signal }).then(r => r.json())
);

searchLatest('rea');
searchLatest('react'); // aborts the previous call

const latest = takeLatest(async (signal, id) => {
  const res = await fetch(`/user/${id}`, { signal });
  return res.json();
});

const user = await latest(42);