JavaScript · Async JavaScript · Mid-Level · Scenario
How do you cancel in-flight async work in the browser, and what cannot be cancelled?
Short Interview Answer
Use `AbortController`/`AbortSignal` with `fetch` and many APIs; pure JS promises cannot be forcibly cancelled mid-executor once running.
Detailed Explanation
Create a controller, pass `signal` to `fetch`, and call `abort()` on navigation/unmount. Listen for `abort` events for cleanup. Libraries should accept signals. Note: aborting rejects fetch with `AbortError` — handle without treating as a hard failure in UI. Timers can be cleared; WebSocket/streams have their own close. A raw `new Promise(executor)` keeps running unless the executor cooperatively checks a signal. Design APIs to be cancellation-aware from day one in SPAs.
Example
const ac = new AbortController();
fetch('/api/data', { signal: ac.signal }).catch((err) => {
if (err.name === 'AbortError') return;
throw err;
});
ac.abort();Interview Tip
Mention cooperative cancellation — shows systems thinking.
Common Mistake
Ignoring aborted fetches and logging them as app errors.