Stop Older JavaScript Requests from Overwriting Newer Results
Reproduce a JavaScript request race, guard against stale search results, and choose when to sequence or cancel asynchronous work.

Yes, JavaScript can have race conditions: two requests can start in one order and finish in another. In a search interface, that can leave an older query’s result on screen after the newer result appeared. If the display should always reflect the latest request, give each request an ID and check it immediately before rendering. If every operation must take effect, sequence the operations instead.
Recognize the stale-result bug
Imagine a user searches for alpha, then changes the query to beta. Both requests are still in progress. If beta finishes first, its result appears, but a later alpha completion can overwrite it. The outcome depends on completion order, not on which query the user entered last. This is the autocomplete failure described in this race-condition example.
Waiting a fixed amount of time before rendering does not establish the order of completion. Instead, decide which request is allowed to change the shared display.
Reproduce requests completing in reverse order
This example replaces network requests with promises whose completion you control. Run the block as written. request saves each promise’s resolver, while renderResults records what the user would see. The calls to search start in query order; the calls to the saved resolvers finish them in the opposite order.
const pending = new Map();
let displayed = "nothing";
function request(query) {
return new Promise((resolve) => {
pending.set(query, resolve);
});
}
function renderResults(results) {
displayed = results;
console.log("Displayed:", displayed);
}
async function search(query) {
const results = await request(query);
renderResults(results);
}
async function main() {
const older = search("alpha");
const newer = search("beta");
pending.get("beta")("beta results");
await newer;
pending.get("alpha")("alpha results");
await older;
console.log("Final:", displayed);
}
main().catch(console.error);
The output is:
Displayed: beta results
Displayed: alpha results
Final: alpha results
The await after resolving beta makes the demonstration unambiguous: the newer search has rendered before the older one is allowed to finish. The final value is wrong for a display that should show the latest query.
Apply only the latest request’s result
Now increment an ID when each search starts. Each call keeps its own ID, but they share latestRequestId. Compare the two immediately before rendering. Run this block separately from the previous one:
const pending = new Map();
let displayed = "nothing";
let latestRequestId = 0;
function request(query) {
return new Promise((resolve) => {
pending.set(query, resolve);
});
}
function renderResults(results) {
displayed = results;
console.log("Displayed:", displayed);
}
async function search(query) {
const requestId = ++latestRequestId;
const results = await request(query);
if (requestId === latestRequestId) {
renderResults(results);
}
}
async function main() {
const older = search("alpha");
const newer = search("beta");
pending.get("beta")("beta results");
await newer;
pending.get("alpha")("alpha results");
await older;
console.log("Final:", displayed);
}
main().catch(console.error);
Now the output is:
Displayed: beta results
Final: beta results
alpha still completes, but its captured ID is no longer current, so it cannot replace beta on this display. The same ID check is used for autocomplete results in the request-ID example. Keep the counter with the state it protects. The check prevents a stale result from being applied there; it does not stop the request or undo anything that request already changed elsewhere.
Choose what must happen to older work
Ignore its result when only the latest answer matters, as with this search display or a profile panel showing the most recently selected user. The request-ID guard allows requests to overlap without letting an older completion choose the visible value.
Sequence it when each operation matters. For example, if two updates must both run and the second must follow the first, discarding the first is not a fix. Start the second update from a promise handler that waits for the first update’s returned promise:
let state = "unset";
function updateState(next) {
return Promise.resolve().then(() => {
state = next;
console.log("Updated:", state);
});
}
Promise.resolve()
.then(() => updateState("draft"))
.then(() => updateState("published"))
.then(() => console.log("Final:", state))
.catch(console.error);
This logs draft, then published, then a final state of published. The second update is not started until the first update’s promise completes. For an update that performs other asynchronous work, return a promise that represents the whole update, so the chain waits for it. Promise chaining is also shown as a way to sequence updates in this example.
Cancel obsolete work when the operation supports cancellation and its result is no longer needed. Outdated fetch requests are one example for which AbortController is proposed. Cancellation addresses the work itself; an ID check addresses whether a completion may render. Choose based on whether older work should be ignored, preserved in order, or stopped.
