In this video, you watch a report from yesterday’s morning routine arrive after today’s and overwrite the Lindqvists’ kitchen status panel. In the last lesson, the problem was a second tap starting the routine twice. This time, the trouble is an old routine that finishes late.
The timings are a scaled-down toy: one second stands in for the night between the two mornings. Tuesday’s report takes five seconds, and Wednesday’s routine starts one second later and reports in two.
Key Points
- Replies can come back in a different order from the one their work started in. Tuesday’s routine started first, but Wednesday’s report came back first, at three seconds, and the status showed it. Tuesday’s came back at five seconds and overwrote it, so the panel ended on yesterday’s report. Outside this toy, too, a newer request can start before an older one answers, and then the older answer can land last.
- The code after an
awaitruns only when its own reply arrives. At five seconds, Node’s event loop moved Tuesday’s timer task onto the call stack, and that task fulfilled its promise. Then a microtask resumed Tuesday’s call where it paused. - A late reply overwrites a newer one. Tuesday’s call wrote its reply into the status, with no idea that a newer routine had started. That’s a race condition, because the result depends on which reply happens to arrive last.
- A run counter tells a late reply from the latest one. Each call adds one to
latestRunand keeps its own number inrunbefore it awaits anything, so Tuesday’srunstays1whilelatestRunmoves on to2. After theawait, it compares the two. If they differ, a newer run has started, so the call ignores its reply and returns without touching the status. - Take a number before you wait, and check it after. Each run takes its number before the
await, as the button claimed the morning in the last lesson. It checks the number after theawait, because the world can change while you wait. Before you use a reply, check that it still belongs to the latest run. - Aborting is the other way out. You could also abort yesterday’s run with an
AbortController, but only if its timer gets the signal and you catch the rejection, as in Make Your Own Functions Cancellable. The counter works even for work you can’t cancel.