Race conditions and stale results
How it works
Asynchronous operations can complete in a different order from the order they started. A stale response can overwrite newer application state even in a single JavaScript agent. Give each request a monotonically increasing version or another identity; apply the result only if it still belongs to the current request. Cancellation may save work but a freshness check remains useful when cancellation is unavailable or arrives too late.
Example 1
let latest = 0;function start() { const id = ++latest; return value => { if (id === latest) console.log(value); }; }const first = start(); const second = start();second("new"); first("old");Expected output in the tested environment:
newOnly the callback holding the current request identity may commit.
Example 2
let resolveOld, resolveNew;const old = new Promise(r=>resolveOld=r); const newer = new Promise(r=>resolveNew=r);let state; old.then(x=>state=x); newer.then(x=>state=x);resolveNew("new"); resolveOld("old");Promise.all([old,newer]).then(()=>console.log(state));Expected output in the tested environment:
oldWithout a freshness guard the later completion overwrites new state.
Common mistake
Do not use request completion order as a proxy for user intent. Capture the identity when starting each request.
Practice
Apply a version guard to the second example and force completions in both orders. Ensure the newer request wins in both cases.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Race conditions and stale results — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
Can stale-result races occur without parallel JavaScript threads?
When should a request identity be captured for freshness checks?
Why retain a freshness guard even when attempting cancellation?
For Race conditions and stale results, what is the console output of example 1 in Node.js 22.16.0?
let latest = 0;function start() { const id = ++latest; return value => { if (id === latest) console.log(value); }; }const first = start(); const second = start();second("new"); first("old");For Race conditions and stale results, what is the console output of example 2 in Node.js 22.16.0?
let resolveOld, resolveNew;const old = new Promise(r=>resolveOld=r); const newer = new Promise(r=>resolveNew=r);let state; old.then(x=>state=x); newer.then(x=>state=x);resolveNew("new"); resolveOld("old");Promise.all([old,newer]).then(()=>console.log(state));