Skip to curriculum
Jump to the editor

14.3. Ignore stale responses (latest request wins)

Medium
Topics
20–30 min

A search box sends a request for "r", then "re", then "rea". The answers can come back in any order: if "r" is slow, its results arrive last and replace the right ones on screen. The rule that fixes it is latest request wins: when a new request starts, the one before it is cancelled, and its answer is never used, even if it still arrives.

Write takeLatest(fn) in take-latest.js. It returns a function that calls fn with an AbortSignal and the caller's arguments. Each new call aborts the call before it: that call's signal aborts, and its promise rejects at once with a DOMException named "AbortError".

Signature

JAVASCRIPT
function takeLatest(fn) // returns a function: (...args) => Promise
  • fn: called as fn(signal, ...args). It may return a promise or a plain value, and may use signal to stop its own work (for example by passing it to fetch).
  • The returned function takes the same arguments as fn without the signal, and returns a promise of fn's result.

Requirements

  1. Each call runs fn at once, with a fresh AbortSignal first and then every argument.
  2. If no newer call starts before fn finishes, the call's promise settles like fn's: same value, or same error.
  3. A new call replaces the call that is still running: that call's signal aborts, and its promise rejects at once with a DOMException named "AbortError".
  4. A replaced call stays rejected whatever fn does later, even when fn ignores the signal, and even if its answer arrives before the newer one. Its late failure is not reported as unhandled.
  5. A call that has already finished is never aborted by the next call.
  6. If fn throws at once, that call's promise rejects with the error (the wrapper does not throw).
  7. Each function takeLatest returns keeps its own latest call.

Examples

JAVASCRIPT
const search = takeLatest((signal, query) =>
  fetch(`/api/search?q=${query}`, { signal }).then((response) => response.json()),
);

search("r").catch((error) => console.log(error.name)); // "AbortError", as soon as the next call starts
search("re").then(show); // only these results reach the screen
JAVASCRIPT
const load = takeLatest((signal, id) => new Promise((resolve) => setTimeout(() => resolve(id), 100)));
const a = load(1);
const b = load(2); // a rejects with AbortError now, even though its timer still fires at 100 ms
// at 100 ms: b resolves with 2
JAVASCRIPT
const first = load(1);
await first;      // 1
const second = load(2);
// first's signal is not aborted: it had already finished

Environment

  • Plain JavaScript in a browser page; the tests call the global takeLatest from take-latest.js.
  • The tests run on a virtual clock that replaces setTimeout. The functions they wrap answer after a delay and, like fetch, reject with signal.reason when their signal aborts, unless a test says they ignore it.
  • Use AbortController for the signals.

Hints

  1. What does the wrapper need to remember between calls, so the next call can cancel the current one?
  2. Aborting a signal tells fn to stop. Does it also settle the promise the caller is waiting on?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…