Web Development Pro | Lesson 034 | Loading, Failure, Cancellation, and Races
Web Development Pro · Lesson 34 of 60
Module 4: Data, modules, and state
In this lesson
Prerequisites and learning outcomes
Complete lesson 33 first. This lesson builds on abortcontroller and stale responses. By the end, you can keep the interface truthful during slow, failed, or superseded requests. Plan 10–15 minutes for the core explanation and additional time for the worked practice.
A later request can finish first
A visitor presses Reload twice. The first request is slow, while the second returns quickly with newer data. If both completions update the page unconditionally, the older result can overwrite the newer one. This is a race condition: completion order differs from request order, and the interface needs a policy for which result is allowed to win.
For the directory, the latest requested load owns the view. Starting a new request should cancel unnecessary old work where possible and prevent stale completions from changing the interface. Cancellation alone is not enough, because a test double or an operation already near completion might still settle. A request identity check provides a separate correctness guard.
Define explicit loading states
Use idle, loading, ready, and error states. The page can then render a truthful message for each. Ready contains the loaded items; error contains a safe explanation. Do not represent failure as an empty successful list, because “no workshops exist” and “we could not retrieve workshops” mean different things to a visitor.
The supplied latest.mjs exports createLatestLoader. It receives a load function and an onState callback, then returns refresh and cancel operations. These dependencies are visible in the example files. The loader coordinates requests without depending directly on the DOM, which makes ordering behavior testable.
export function createLatestLoader(load, onState) {
let requestId = 0;
let active = null;
async function refresh() {
const id = ++requestId;
if (active) active.abort();
const controller = new AbortController();
active = controller;
onState({ phase: 'loading' });
try {
const items = await load(controller.signal);
if (id !== requestId) return;
onState({ phase: 'ready', items });
} catch (error) {
if (id !== requestId) return;
onState(error && error.name === 'AbortError'
? { phase: 'idle' }
: { phase: 'error', message: 'Workshop data could not load.' });
}
}
function cancel() {
requestId += 1;
if (active) active.abort();
onState({ phase: 'idle' });
}
return { refresh, cancel };
}
The incrementing id identifies the request that most recently acquired ownership. Both success and failure check that ownership before publishing state. Cancel also increments the id, so a canceled operation cannot later restore a result even if its underlying implementation ignores the abort signal.
Pass the signal to the real operation
The entry module's load function calls fetch('./workshops.json', {signal}), checks response.ok, and reads JSON. AbortController does not cancel arbitrary work merely because it exists; the operation must receive and honor its signal. A new controller is created for each refresh because an aborted signal cannot be reset for reuse.
Aborting a fetch can reject with an AbortError. The example treats that as an idle outcome for the active request rather than an ordinary service failure. Superseded requests are ignored first by their id check, so they do not flash an error after the newer load has begun. The policy is explicit and can be tested without relying on network timing.
The code does not claim that aborting a client request reverses an action already processed by a server. This lesson loads read-only data. Canceling a payment or submission would need a different server-side contract; a stopped browser request is not a universal undo operation.
Render state in one place
The complete app defines an onState renderer that clears old output while loading, displays joined titles when ready, shows a retry message on error, and explains cancellation in idle. Reload and Cancel are native buttons. Their listeners call the returned operations without adding new listeners during rendering.
Clearing old output is a deliberate choice for this simple example. Another product might retain old data with an explicit “refreshing” or “out of date” label. Either approach can be valid if the status is truthful. Quietly showing old data as if it were fresh is the misleading outcome to avoid.
A cancel action should not leave a permanent loading message. Nor should an old request's finally block remove the loading state of a newer request. Centralizing state publication behind the identity check avoids that common cleanup race. If you add separate flags later, include ownership in their update rules too.
Test ordering without real delays
Create two controllable promises. Start the first refresh, then the second. Resolve the second with newer records, then resolve the first with older records. The final state must remain the newer records. This directly tests the race policy instead of hoping a slow network happens to reproduce it.
Also test a current failure, explicit cancellation, and a superseded failure. Inspect the first signal's aborted property after starting the second request. That proves the loader attempted cancellation, while the stale-result test proves correctness even when the supplied load function ignores the signal.
The runtime tests exercise real Promise scheduling and AbortController signals in Node with injected loaders. They do not execute browser fetch cancellation, actual HTTP timing, or visible status announcements. The app's HTML and module connections receive static checks; manual browser testing remains necessary for the full experience.
Worked practice
Worked exercise 1: Prevent stale success
Task: Request A starts first, request B starts second, B finishes first, then A finishes. Worked answer: only B may publish its result because its id matches the current requestId. A's late success returns without changing the view.
Worked exercise 2: Explain cancellation scope
Task: A learner believes aborting fetch guarantees the server never received a request. Worked answer: abort stops client-side work where supported, but cannot guarantee reversal of server processing. This example is read-only; consequential actions need their own server cancellation or idempotency design.
Worked exercise 3: Test an ignored signal
Task: A mocked loader ignores AbortSignal and eventually resolves after Cancel. Worked answer: the request id still prevents its completion from publishing ready state. Cancellation and ownership checks provide different protections and should both be tested.
Knowledge check
Question 1
Why use a request id as well as AbortController? A) To guarantee the older request never reached a server. B) To prevent stale publication even if cancellation is ineffective. C) To make a canceled signal usable for the next load. D) To force responses to complete in request order.
Check question 1: answer and explanation
Answer: B. Ownership guards correctness independently of cancellation behavior.
Question 2
What must receive the signal for fetch cancellation? A) The fetch options used for that request. B) Only the onState callback after completion. C) Only a new controller created without passing it to fetch. D) Only the previously completed request.
Check question 2: answer and explanation
Answer: A. An unused controller does not affect an unrelated operation.
Question 3
What should a superseded request's error do here? A) Replace the newer result with an error. B) Clear the newer request's loading state. C) Be ignored after the ownership check. D) Restart every request automatically.
Check question 3: answer and explanation
Answer: C. The current request owns the visible state.
Question 4
Can an aborted signal be reset for another refresh? A) Yes, by assigning false to aborted. B) Yes, by awaiting its rejected request before reuse. C) Yes, when the next fetch uses the same URL. D) No; create a new controller.
Check question 4: answer and explanation
Answer: D. Abort signals have a one-way aborted state.
Question 5
Which test best exposes this race policy? A) Resolve two controlled requests in reverse order. B) Check one fast success only. C) Assert that abort was called without settling the older promise. D) Resolve the requests only in their original start order.
Check question 5: answer and explanation
Answer: A. Controlled ordering makes the stale-completion condition deterministic.