Cancel fetch and prevent stale results
Quick answer
AbortController requests cancellation through its signal. Pass the signal to fetch and separately guard UI updates against stale results from earlier requests.
How it works
Call controller.abort() to signal cancellation. An already aborted default signal causes a fetch rejection with AbortError; other reasons may differ. Do not reuse an aborted controller for a new request. Cancellation is cooperative and cannot undo a server operation already performed. A monotonically increasing request ID can prevent late results from replacing current state.
Local examples
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {const c=new AbortController();c.abort();try{await fetch("data:text/plain,x",{signal:c.signal});}catch(e){console.log(e.name,c.signal.aborted);}})()Expected console output:
AbortError trueThe request starts with an already aborted signal.
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {let latest=2;const out=[];function publish(id,value){if(id===latest)out.push(value);}publish(2,"new");publish(1,"old");console.log(out.join(","));})()Expected console output:
newThe older completion cannot overwrite the current result.
Common mistakes
Do not assume abort means a POST never reached the server. Treat freshness checks and cancellation as different safeguards.
Guided practice
Simulate two overlapping searches and ensure only the latest request may publish a result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cancel fetch and prevent stale results — Knowledge Check
Apply the concept and reason about the example output.
Can an aborted controller be reset for a fresh request?
Does client cancellation undo an already committed server mutation?
What prevents a late stale response from updating current UI state?
What is the expected console output of Cancel fetch and prevent stale results example 1?
(async () => {const c=new AbortController();c.abort();try{await fetch("data:text/plain,x",{signal:c.signal});}catch(e){console.log(e.name,c.signal.aborted);}})()What is the expected console output of Cancel fetch and prevent stale results example 2?
(async () => {let latest=2;const out=[];function publish(id,value){if(id===latest)out.push(value);}publish(2,"new");publish(1,"old");console.log(out.join(","));})()