Practical tools and techniques · Lesson 40 of 45
Cancellation and stale results
AbortController and search result races.
8 minutes1 games
When a user starts another search before the first finishes, an older response can overwrite the newer result. AbortController provides a signal to pass to a request; abort requests cancellation. A request sequence number also helps ensure only the latest result is applied.
JavaScript
const controller = new AbortController()
controller.signal.addEventListener("abort", () => {
console.log("Cancelled")
}, { once: true })
console.log(controller.signal.aborted)
controller.abort()
console.log(controller.signal.aborted)JavaScript
let controller
let latest = 0
async function search(query) {
controller?.abort()
controller = new AbortController()
const id = ++latest
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {signal: controller.signal})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
if (id === latest) console.log(data)
} catch (err) {
if (err.name !== "AbortError" && id === latest) console.error(err)
}
}Integration example for an app providing /api/search; this endpoint is not supplied by the lesson editor.
First search
New search aborts previous
Check request id
Apply only the latest result
Exercise
Create and abort an AbortController, then print signal.aborted.
Expected output: true
JavaScript
Learn more from
Played 0 of 1 games
Sign in to save your progress and earn XP.