0
APIs & Async · Advanced Async
New technique
Cancelling with AbortController
Sometimes you call the runner back halfway to the mines. The user left the page? Cancel the request!
A request you no longer need still costs bandwidth, and its response can still land and change the screen. So modern code cancels requests: when the user leaves a page, closes a dialog or starts a new search.
The tool is an AbortController. It owns a signal that you pass to fetch in the options. Calling controller.abort() later cancels every request that got that signal.
const controller = new AbortController();
fetch("/api/search?q=axe", { signal: controller.signal });
cancelButton.addEventListener("click", () => controller.abort());- Pass
controller.signal, not the controller itself: the controller is the button you press, the signal is what the request listens to. - One controller can cancel several requests: give them all the same signal.