CKTIS / JavaScript
Generation ticket cancellation pattern
Use a generation ticket to let only the most recently started operation update state, provided it is still current. Older work can finish without overwriting that state.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
let current = null;
async function run(load, commit) {
const ticket = {};
current = ticket;
const result = await load();
if (ticket !== current) return;
commit(result);
}
function invalidate() {
current = null;
}In a search box, a response for an earlier query can arrive after the response for a newer query. The Generation ticket cancellation pattern controls which operation may update state. It is a design pattern, not special JavaScript syntax or a built-in API.
On each start, create a fresh object ticket and store it in current. The test ticket === current compares object identity, not contents. A new start replaces the current ticket; setting current = null invalidates it without starting new work, such as when closing a view. Keep a separate current for each independently updated resource.
After await, check the ticket immediately before changing state. If another await intervenes, check again before writing. A rejected promise throws at await, so guard error displays and changes to loading indicators in finally too. Handle or propagate errors from the current operation; do not let a stale run change the UI.
This is logical cancellation: it does not stop the work or undo effects that already happened. If the API accepts a signal, create a new AbortController for each operation and pass its signal property to the API. After invalidating the operation’s ticket, call abort() on that same controller. Keep the ticket check because not all work observes the signal. AbortController is a web platform API, not part of ECMAScript; check support in your target runtime.
Examples
(async () => {
let current = null;
let visible = '(empty)';
async function show(pending) {
const ticket = {};
current = ticket;
const result = await pending;
if (ticket !== current) {
console.log(`skip: ${result}`);
return;
}
visible = result;
console.log(`commit: ${visible}`);
}
let finishOld;
const oldResult = new Promise((resolve) => { finishOld = resolve; });
const oldRun = show(oldResult);
await show(Promise.resolve('new'));
finishOld('old');
await oldRun;
console.log(`visible: ${visible}`);
})();Result
commit: new skip: old visible: new
`finishOld('old')` is called only after `new` has been committed. `skip: old` is a diagnostic message, not a change to `visible`.
Related lessons
- JavaScript · Lesson 14 · Advanced · Version: 4