Why did AbortController not stop my fetch?
Pass the controller’s signal to fetch. Creating an AbortController beside a request does not connect it to that request.
Handle cancellation separately from other failures. AbortSignal.timeout can set a deadline, but stopping the client wait does not undo work the server already performed.
Understand it. Then fix it.
Connect the signal.
The request must receive the controller's signal. Calling abort then rejects that fetch. A controller next to a request has no effect on it.
const c = new AbortController();
const request = fetch("/report", {
signal: c.signal
});
c.abort();Cancellation is a result to handle.
Catch cancellation separately from real failures. With the default abort reason, the error is named AbortError. Other failures still need reporting.
try {
await request;
} catch (error) {
if (error.name !== "AbortError") {
throw error;
}
}Need a deadline? Use a timeout signal.
For a deadline, fetch also accepts AbortSignal dot timeout. This example stops waiting after five seconds and needs timeout error handling too.
await fetch("/report", {
signal: AbortSignal.timeout(5000)
});Client stopped. Server may continue.
Neither approach rolls back server work already performed. Use a new signal for a new attempt. Cancellation and undo are different contracts.
Code blocks are teaching excerpts. Keep the surrounding error handling and application requirements.
Save the code excerpts ↓Read the full transcript
Why did abort not stop my request? I created the controller. Apparently management by proximity was not enough. The request must receive the controller's signal. Calling abort then rejects that fetch. A controller next to a request has no effect on it. Catch cancellation separately from real failures. With the default abort reason, the error is named AbortError. Other failures still need reporting. For a deadline, fetch also accepts AbortSignal dot timeout. This example stops waiting after five seconds and needs timeout error handling too. Neither approach rolls back server work already performed. Use a new signal for a new attempt. Cancellation and undo are different contracts. The client left the meeting. The server is still making slides.