JavaScript · The language round
How do you fetch data and cancel a request?
Short answer
fetch returns a promise for a Response and does not reject on HTTP error statuses. Check response.ok, parse the body, and pass an AbortController signal to cancel the request.
A network failure rejects the fetch promise, but a 404 or 500 does not. That distinction is the first thing to get right.
async function loadUser(id, signal) {
const response = await fetch("/api/users/" + id, { signal });
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
}Cancelling with AbortController
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch("/api/search", {
signal: controller.signal,
});
const data = await response.json();
console.log(data);
} catch (error) {
if (error.name === "AbortError") {
console.log("request cancelled");
} else {
throw error;
}
} finally {
clearTimeout(timeout);
}response.okis true for status codes 200 to 299response.json()returns a promise and can reject on invalid JSON- AbortController can cancel one or many requests that share its signal
- Aborting rejects the fetch promise with an
AbortError
mode, credentials and cache. They are not automatic.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Does `fetch` reject on a 500 response?
- 2How do you implement a request timeout?
- 3What happens to the promise when a request is aborted?
- 4How do you send cookies with `fetch`?
Say it in the interview
fetch returns a promise that resolves to a Response for any HTTP status, so I check response.ok before parsing. Network failures reject, but 404 and 500 do not. I pass an AbortController signal to cancel stale requests or implement a timeout, and I treat an AbortError separately from a real failure. I also parse the body with response.json or response.text.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.