The function calls fetch(...) but never returns the promise, so callers get undefined: await getUser() resolves to nothing, and errors are unhandled rejections the caller can't catch. Often there's a second missing return inside .then((res) => { res.json(); }), because an arrow with braces needs an explicit return. The fix is return fetch(url).then((res) => res.json()), or async/await with return res.json(). Then mention what interviewers probe next: fetch doesn't reject on HTTP errors (a 404 resolves with res.ok === false), so check ok. A production helper also adds a timeout with AbortController and retries only failures worth retrying.
Fix a buggy fetch helper: the provided function may look right but doesn't return the promise from fetch(...). You're expected to spot it.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
A function that starts async work must return its promise, or nothing can wait for it or catch its errors. Both returns matter: the function's, and the arrow's, since { res.json(); } evaluates the promise and throws it away. With async/await, write return res.json(). The checks show the buggy version returning undefined while the request still goes out.
// The bug: fetch() starts the request, but the promise isn't returned, so the caller gets// undefined (and can't catch errors either)://// function getUser(id) {// fetch(`/api/users/${id}`).then((res) => { res.json(); });// }//// Two returns were missing: the function's, and the arrow's (braces need an explicit return).function getUser(id) {return fetch(`/api/users/${id}`).then((res) => res.json());}// The same with async/await.async function getUserAsync(id) {const res = await fetch(`/api/users/${id}`);return res.json();}
passes 3 checks run on every build, against the native method where there is one
- the fixed helpers return the data
- the buggy version returns undefined
- errors reach the caller, who can catch them
fetch rejects (with a TypeError) only when the request itself fails: no network, CORS blocked, or aborted. A 404 or 500 is a successful fetch of an error response, so check res.ok and throw an error that carries the status and body. A 204 has no body, so res.json() would throw.
class HttpError extends Error {constructor(response, body) {super(`HTTP ${response.status}`);this.name = 'HttpError';this.status = response.status;this.body = body;}}async function getJson(url, init) {const res = await fetch(url, init);// fetch rejects only when the request fails (network, CORS, abort). A 404 or 500 resolves,// with res.ok === false, so it has to be checked.if (!res.ok) {const body = await res.text().catch(() => '');throw new HttpError(res, body);}if (res.status === 204) return null; // No Content: res.json() would throw on the empty bodyreturn res.json();}
passes 4 checks run on every build, against the native method where there is one
- a 404 rejects with the status and body
- success returns the parsed JSON; 204 returns null
- network failures still reject as TypeError
- options are passed to fetch
Each attempt gets its own AbortController, aborted after timeout with a TimeoutError. The caller's signal is forwarded to it. Retry only what might succeed next time: timeouts, network errors, 5xx and 429, never a 4xx. Wait backoff · 2^attempt between attempts. If the caller aborts, stop at once, even mid-wait, and clear every timer. (AbortSignal.timeout() and AbortSignal.any() do the timer and the merge natively in current browsers.)
class HttpError extends Error {constructor(response, body) {super(`HTTP ${response.status}`);this.name = 'HttpError';this.status = response.status;this.body = body;}}async function getJson(url, init) {const res = await fetch(url, init);// fetch rejects only when the request fails (network, CORS, abort). A 404 or 500 resolves,// with res.ok === false, so it has to be checked.if (!res.ok) {const body = await res.text().catch(() => '');throw new HttpError(res, body);}if (res.status === 204) return null; // No Content: res.json() would throw on the empty bodyreturn res.json();}const sleep = (ms, signal) =>new Promise((resolve, reject) => {if (signal?.aborted) return reject(signal.reason);const id = setTimeout(resolve, ms);signal?.addEventListener('abort', () => { clearTimeout(id); reject(signal.reason); }, { once: true });});// A timeout per attempt, retries with exponential backoff for failures worth retrying, and the// caller's signal cancels everything, including the wait between attempts.async function fetchJson(url, { retries = 2, timeout = 5000, backoff = 300, signal, ...init } = {}) {for (let attempt = 0; ; attempt++) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(new DOMException('Request timed out', 'TimeoutError')), timeout);const onAbort = () => controller.abort(signal.reason);signal?.addEventListener('abort', onAbort, { once: true });try {if (signal?.aborted) throw signal.reason;return await getJson(url, { ...init, signal: controller.signal });} catch (error) {const retryable =error.name === 'TimeoutError' ||error instanceof TypeError || // network failure(error instanceof HttpError && (error.status >= 500 || error.status === 429));if (!retryable || attempt >= retries) throw error;await sleep(backoff * 2 ** attempt, signal); // rejects at once if the caller has aborted} finally {clearTimeout(timer);signal?.removeEventListener('abort', onAbort);}}}
passes 6 checks run on every build, against the native method where there is one
- retries a 503 with backoff, then succeeds
- a 404 is not retried
- gives up after the last retry with the last error
- a request that hangs times out
- the caller's abort stops it, without retrying
- a caller's own timeout signal isn't retried either
The missing return is a classic agent bug
Generated helpers often wrap fetch in a function body with braces and drop the return. The code looks finished, type-checks as void in plain JavaScript, and fails only when a caller awaits it.
fetch resolves on 404
MDN calls this out explicitly: the promise only rejects on network errors, so a res.ok check is part of every correct fetch wrapper.
Retry with backoff
Cloud APIs ask clients to retry 429s and 5xx with exponential backoff (often with random jitter) so retries don't hammer a struggling server.
Missing
returnbeforefetch(...), or inside a braced arrow callback.Treating any resolved fetch as success without checking
res.ok.Calling
res.json()on a 204 or an error page that isn't JSON.Retrying 4xx errors, or retrying forever with no backoff.
A timeout
setTimeoutthat's never cleared after success.
How would you cancel a request when a React component unmounts?
Create an AbortController in the effect, pass its signal to fetch, and call controller.abort() in the cleanup. Ignore the resulting AbortError in the catch.
Why add jitter to backoff?
If many clients fail at the same moment, identical backoff makes them all retry together. A random delay spreads the retries out.
How do you avoid duplicate requests for the same URL?
Keep a map from URL to the in-flight promise and return it to later callers. Delete the entry when it settles.