A controller connects the pure pieces
Our controller receives search and render dependencies. It owns state, a generation counter, the active AbortController, and a disposed flag. Its load method cleans the query, invalidates older work, starts a request, decodes the returned books, and sends a transition only if the attempt is still current.
A small send(action) helper updates state with the reducer and calls render. Keeping those together avoids a state update that forgets to refresh the interface. The optional initial saved array must already satisfy the book contract; decode restored storage before passing it. The renderer must treat state as read-only; getState returns the current snapshot by convention, not a frozen deep copy.
There are two guards after asynchronous work: disposed prevents updating a departed view, and mine !== generation prevents an older attempt from replacing a newer one. The error path needs the same checks. Cancel invalidates the generation as well as aborting, so when the abort rejection arrives it is stale and does not become a service error on the screen. The order of those two lines inside cancel doesn't matter: the rejection is handled after await, in a later microtask, by which time both have run. What matters is that cancel bumps the generation at all; abort alone would let the rejection through as an error.
Read the smaller controller below before opening the full project. It deliberately omits cancellation and schema validation to isolate the ownership rule; the downloadable controller includes them. The dependencies make it possible to test this flow with no DOM and no timer sleeps.
Predict and trace
Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.
async function main() {
function createLoader(search, render) {
let generation = 0;
return async function load(query) {
const mine = ++generation;
render("loading");
try {
const value = await search(query);
if (mine === generation) {
render(value);
}
} catch (error) {
if (mine === generation) {
render(error.message);
}
}
};
}
const messages = [];
const load = createLoader(
async () => "ready",
text => messages.push(text)
);
await load("web");
console.log(messages.join(", "));
}
main();Check your prediction
loading, readyThe search double fulfills predictably. The renderer records transitions instead of touching a page.
Run the actual controller without a webpage
The console lab below combines the same controller.js and model.js used by the final app inside an async main entry point. The short entry code at the top supplies a controlled search function and a renderer that prints status. The first load returns a valid book; the second returns a wrong-type title. Predict the sequence, then follow each status to its reducer action.
Check your prediction
loading
ready
Notes
loading
error
Each book needs an id and titleOnly valid, trimmed books reach ready. The invalid response goes through the controller's guarded catch into failed, rather than being rendered as a book. No DOM or live request is involved.
This single-program lab puts its entry code first, followed by the function definitions. Function declarations using function can be called earlier in the same scope; this is called hoisting. You do not have to organize your own code this way. The lab preserves the short, editable entry at the top while keeping the actual core functions available below it.
The console lab combines files because this editor’s file-tab mode does not support top-level await. The synchronous module example on Day 2 is unaffected; the downloaded project uses ordinary ES modules and runs controller-demo.js with Node. You do not need to install anything to practice here.
On your first pass, trace one successful load from the entry code, then trace the invalid response. You do not need to transcribe the combined definitions: the goal is to recognize where each earlier lesson participates.
Read the program in this order:
- In the entry code at the top, find the injected search and render dependencies.
- In createController below it (from controller.js), follow load from the loading action through search, decoding, and the current-generation check.
async load(text) { ... }is an async method stored under load.active?.abort()calls abort only when an active controller exists. - In the model functions (from model.js), find which fields each action changes and which saved fields it preserves.
- Return to the entry code, change the second title from 42 to a string, and predict which error output disappears. Run again.
This is the final app's data flow before adding HTML. Keep the smaller sketch above as a way to isolate ownership, not as a replacement missing the full controller's guards. In the downloaded project, node controller-demo.js runs this same console entry point.
Build it yourself
A guarded lookup controller
createLookup({ find, render }) shows one book by id. The starter works for a single lookup but has none of the controller's guards. Make show(text) follow these rules: a blank id renders error: enter an id without calling find; otherwise render loading, then ready <title>, missing <id> (when find gives undefined) or error: <message>, but only if this is still the newest show and the controller has not been disposed. After dispose(), show does nothing. The test drives find with deferred promises: a blank id, then a slow "js" overtaken by a fast "web" (the old one fails late), then a lookup interrupted by dispose. It should print:
error: enter an id
loading
loading
ready The Web
loadingasync function main() {
function createLookup({ find, render }) {
// Unguarded first version: add the blank check, generation and dispose.
return {
async show(text) {
const id = text.trim();
render("loading");
try {
const book = await find(id);
render(book === undefined ? `missing ${id}` : `ready ${book.title}`);
} catch (error) {
render(`error: ${error.message}`);
}
},
dispose() {}
};
}
function deferred() {
let resolve;
let reject;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
const pending = {};
const screen = [];
const lookup = createLookup({
find(id) {
pending[id] = deferred();
return pending[id].promise;
},
render: text => screen.push(text)
});
lookup.show(" "); // not awaited: a blank id must not start a search
const slow = lookup.show("js");
const fast = lookup.show("web");
pending.web.resolve({ title: "The Web" });
await fast;
pending.js.reject(new Error("timeout"));
await slow;
const late = lookup.show("css");
lookup.dispose();
pending.css.resolve(undefined);
await late;
console.log(screen.join("\n"));
}
main();Hint 1: the idea
This is the full controller's ownership rule on a smaller scale. Each show takes a number when it starts; when its await returns, it may only render if that number is still the latest and nobody has called dispose. Both the success and the failure path need that check.
Hint 2: a first step
Run the starter and compare: the blank id renders loading, the late "js" failure renders error: timeout after "The Web", and the disposed lookup renders missing css. Fix the first one with an early return before render("loading"), then add let generation = 0; and const mine = ++generation; for the second.
Show one solution
async function main() {
function createLookup({ find, render }) {
let generation = 0;
let disposed = false;
return {
async show(text) {
if (disposed) {
return;
}
const id = text.trim();
const mine = ++generation;
if (id === "") {
render("error: enter an id");
return;
}
render("loading");
try {
const book = await find(id);
if (disposed || mine !== generation) {
return;
}
render(book === undefined ? `missing ${id}` : `ready ${book.title}`);
} catch (error) {
if (disposed || mine !== generation) {
return;
}
render(`error: ${error.message}`);
}
},
dispose() {
disposed = true;
}
};
}
function deferred() {
let resolve;
let reject;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
const pending = {};
const screen = [];
const lookup = createLookup({
find(id) {
pending[id] = deferred();
return pending[id].promise;
},
render: text => screen.push(text)
});
lookup.show(" "); // not awaited: a blank id must not start a search
const slow = lookup.show("js");
const fast = lookup.show("web");
pending.web.resolve({ title: "The Web" });
await fast;
pending.js.reject(new Error("timeout"));
await slow;
const late = lookup.show("css");
lookup.dispose();
pending.css.resolve(undefined);
await late;
console.log(screen.join("\n"));
}
main();error: enter an id
loading
loading
ready The Web
loadingmine !== generation drops the late "js" failure because "web" took a newer number; without it on the catch path, error: timeout would replace "The Web". The disposed flag is checked after the await as well as at the start, so the "css" lookup that began before dispose() still renders nothing when it finishes. The blank check returns before render("loading") and before find, so an empty input never starts work. These are the same two guards as in createController, minus its AbortController.
Explain before moving on
Why must cancel invalidate the generation, not just abort? What would an unconditional render in finally break?
Completion is saved in this browser only. It does not measure mastery.