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.
Code
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 redisThe 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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.