JavaScript Interview Question #91
How can you cancel a fetch request?
Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate
Quick Interview Answer
Use AbortController. Pass the controller's signal to fetch, then call controller.abort when the request should be canceled.
Detailed Explanation
Use AbortController. Pass the controller's signal to fetch, then call controller.abort when the request should be canceled.
Cancellation is useful for search-as-you-type interfaces, navigation changes, component cleanup, or explicit user cancellation. Code should distinguish expected aborts from genuine network failures when presenting errors.
Code Example
const controller = new AbortController();
const request = fetch("/api/products", {
signal: controller.signal
});
// Later:
controller.abort();
try {
await request;
} catch (error) {
if (error.name === "AbortError") {
console.log("Request cancelled");
}
}