Skip to article content
FrontendXLesson 25 / 30

Fetch and Network Requests

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

intermediate · about 45 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Read a response correctly and detect HTTP errors.
  • Cancel a request with AbortController and add a timeout.
  • Build a small resilient request helper.

Overview

#

fetch resolves on any HTTP status

fetch returns a promise that resolves as soon as headers arrive, even for a 404 or a 500. It only rejects on a network failure. You must check response.ok and read the body yourself, usually with response.json().

snippet.js
const res = await fetch('/api/user');
if (!res.ok) throw new Error('HTTP ' + res.status);
const data = await res.json();

Requests and cancellation

Pass an options object to set the method, headers and body. An AbortController produces a signal that cancels the request; combining it with setTimeout gives a timeout. Cancellation rejects the promise with an AbortError, which should be handled separately from a real failure.

snippet.js
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
try {
  const res = await fetch('/api/slow', { signal: controller.signal });
} finally {
  clearTimeout(timer);
}

Errors and resilience

Distinguish a network error, an HTTP error and a parse error, because the recovery differs. Retry only idempotent requests and only on transient failures, with a backoff, and never retry a request that already succeeded. CORS blocks are browser policy, not server bugs, and the fix belongs on the server headers.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What happens when fetch receives a 404 response?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    const res = await fetch('/missing');
    console.log(res.ok, res.status);
    Choose the best answer
  2. Exercise 2Explain

    Explain why fetch does not reject on an HTTP error status.

    starter.text
    const res = await fetch('/api');

    Reveal the reference answer
    reference.text
    fetch models a completed network exchange, not application success. A 404 or 500 is a valid HTTP response with headers and a body, so the promise resolves and the caller decides what the status means. The promise rejects only when the request itself fails, such as a DNS error or a dropped connection. That is why every caller must check response.ok.

    Authored expected output: the promise resolves with the response

    The answer should separate transport success from application success and name response.ok as the required check.

  3. Exercise 3Implement

    Implement `fetchJson(url, options)` so it throws on a non-ok status and returns the parsed JSON body.

    starter.javascript
    async function fetchJson(url, options) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    async function fetchJson(url, options) {
      const res = await fetch(url, options);
      if (!res.ok) throw new Error('HTTP ' + res.status);
      return res.json();
    }

    Authored expected output: the parsed body, or a thrown error on a bad status

    Checking res.ok turns an HTTP error into a rejected promise so the caller's catch handles it. Only a successful response is parsed.

  4. Exercise 4Debug

    This call is meant to read the body but logs undefined. Find and fix the bug.

    starter.javascript
    async function load() {
      const res = fetch('/api');
      const data = res.json();
      console.log(data);
    }

    Reveal the reference answer
    reference.javascript
    async function load() {
      const res = await fetch('/api');
      const data = await res.json();
      console.log(data);
    }

    Authored expected output: the parsed body

    fetch and json both return promises. Without await, res is a pending promise and calling json on it fails or yields a promise, so data is not the body. Awaiting both resolves the chain.

  5. Exercise 5Test

    Write assertions that prove a timeout aborts a slow request and that an aborted request throws an AbortError.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }

    Reveal the reference answer
    reference.javascript
    async function withTimeout(promise, ms) {
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), ms);
      try { return await promise(controller.signal); }
      finally { clearTimeout(timer); }
    }
    let name = '';
    try {
      await withTimeout((signal) => new Promise((_, reject) => {
        signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')));
      }), 10);
    } catch (e) { name = e.name; }
    assertEqual(name, 'AbortError', 'aborted request reports AbortError');
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    The signal fires an abort event after the timer, and the promise rejects with an AbortError. Checking the error name lets the caller ignore a deliberate cancellation.

  6. Exercise 6Interview

    How would you design a resilient request layer for a frontend app?

    Reveal the reference answer
    reference.text
    I wrap fetch in one helper that checks response.ok, parses the body once, attaches auth headers and maps errors to a small set of types. I add a timeout with AbortController, retry only idempotent requests on transient failures with backoff plus jitter, and cancel in-flight requests when a component unmounts. I keep retry policy in one place so it is consistent and observable.

    The answer should name a single helper, ok checks, typed errors, timeout, selective retry with backoff and cancellation.

Common misconceptions

#
  • fetch rejects its promise when the server returns a 404.
  • response.json() can be called more than once on the same response.
  • Retrying every failed request is always safe.

Follow-up practice

#
  • javascript-foundations-async-patterns
  • javascript-foundations-errors-and-debugging

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.