14.3. Ignore stale responses (latest request wins)
Topics
This question is in
14. Timeouts, retries and concurrencyA 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
function takeLatest(fn) // returns a function: (...args) => Promisefn: called asfn(signal, ...args). It may return a promise or a plain value, and may usesignalto stop its own work (for example by passing it tofetch).- The returned function takes the same arguments as
fnwithout the signal, and returns a promise offn's result.
Requirements
- Each call runs
fnat once, with a freshAbortSignalfirst and then every argument. - If no newer call starts before
fnfinishes, the call's promise settles likefn's: same value, or same error. - A new call replaces the call that is still running: that call's signal aborts, and its promise rejects at once with a
DOMExceptionnamed"AbortError". - A replaced call stays rejected whatever
fndoes later, even whenfnignores the signal, and even if its answer arrives before the newer one. Its late failure is not reported as unhandled. - A call that has already finished is never aborted by the next call.
- If
fnthrows at once, that call's promise rejects with the error (the wrapper does not throw). - Each function
takeLatestreturns keeps its own latest call.
Examples
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 screenconst 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 2const first = load(1);
await first; // 1
const second = load(2);
// first's signal is not aborted: it had already finishedEnvironment
- Plain JavaScript in a browser page; the tests call the global
takeLatestfromtake-latest.js. - The tests run on a virtual clock that replaces
setTimeout. The functions they wrap answer after a delay and, likefetch, reject withsignal.reasonwhen their signal aborts, unless a test says they ignore it. - Use
AbortControllerfor the signals.
Hints
- What does the wrapper need to remember between calls, so the next call can cancel the current one?
- Aborting a signal tells
fnto 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