fetch, AbortController & Retries — JavaScript interview guide
fetch, AbortController & Retries
fetch returns a promise for a Response. It only rejects on network failure, so you must check res.ok yourself. AbortController cancels requests.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
fetch runs in the browser — and AbortController can cancel it
▶const controller = new AbortController();23fetch("/api/search?q=re", { signal: controller.signal })4.then((res) => res.json())5.then((data) => console.log(data))6.catch((err) => console.log(err.name));78controller.abort(); // user typed again
| controller | AbortController |
| signal.aborted | false |
empty
Waits until the Call Stack is empty. Microtasks always go first.
empty
empty
nothing printed yet
What happens:An AbortController gives us a signal we can pass to fetch, and an abort() button we can press later.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
A safe fetch helper
Check status, parse JSON, and support cancelling.
async function getJSON(url, { signal } = {}) {
const res = await fetch(url, { signal });
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
}
const controller = new AbortController();
getJSON("/api/search?q=re", { signal: controller.signal });
controller.abort(); // cancels — the promise rejects with AbortErrorAvoid race conditions in search
When the user types fast, an old slow response can arrive after a newer one. Abort the previous request before starting a new one.
Remember this
- 404 and 500 do NOT reject fetch.
- Abort old requests on new input or unmount.
- Use exponential backoff for retries.
Interview questions
Does fetch reject on a 404?
No. fetch rejects only on network errors or abort. A 404 resolves with res.ok === false.
Practice
- Write fetchWithRetry(url, retries, delay) with exponential backoff.
- Add a timeout to fetch using AbortSignal.timeout.
Keep learning
More in Browser & Practical JS