Latest-Wins Search Ignores Stale Responses

Each request records a sequence ticket and responses check it before applying, so type-ahead searches drop stale results instead of flashing old data.

JavascriptResilience

Code

snippet
let requestSeq = 0;

async function search(query) {
  const ticket = ++requestSeq;
  console.log("start", query);
  await new Promise((resolve) => setTimeout(resolve, 30));
  // A newer request was started while this one was in flight
  if (ticket !== requestSeq) {
    console.log("stale, drop", query);
    return null;
  }
  console.log("fresh, apply", query);
  return `results for ${query}`;
}

async function main() {
  const first = search("re");
  const second = search("red");
  const third = search("redis");
  const landed = await Promise.all([first, second, third]);
  console.log("applied:", landed.at(-1));
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

start re
start red
start redis
stale, drop re
stale, drop red
fresh, apply redis
applied: results for redis

The logic unrolled

The code’s whole job belongs to the functions search and main.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Caveats

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Using it

Entry signature: async function search(query)

Expect labeled output — start, stale, drop, fresh, apply — when the file runs.

Start the program and main runs search one after another.

Key statements

await new Promise((resolve) => setTimeout(resolve, 30));
const landed = await Promise.all([first, second, third]);
return `results for ${query}`;

Interactive Tools for This Topic

FAQ

What does Latest-Wins Search Ignores Stale Responses print when run?
Execute the whole file; each printed line is prefixed with a label like `start`, `stale, drop`, `fresh, apply`.