Advanced Fetch API Patterns

Published by Brayan K

Master retry logic, timeouts, AbortController, and concurrency control for production-grade network handling

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A retry starts another operation; it does not repair the first promise

Start by deciding what may be repeated, which failures are eligible and when to stop. These examples use real Response and AbortSignal objects with controlled transports, so no service, credentials or changing network is needed. They test the wrapper’s policy; they do not establish a remote server’s behaviour, CORS configuration or an application’s safe retry budget.

let calls = 0;
const statuses = [503, 200];
async function transport() {
  calls++; // Each call creates a fresh response, just as another request would.
  const status = statuses.shift();
  return new Response(JSON.stringify({ ready: status === 200 }), {
    status, headers: { "Content-Type": "application/json" }
  });
}
let value;
for (let attempt = 1; attempt <= 2; attempt++) {
  const response = await transport();
  if (response.ok) { value = await response.json(); break; }
  await response.body.cancel(); // Discard the failed response body before another attempt.
}
console.log(calls, value.ready);

// ✅ Expected output:
// 2 true

This first example isolates attempt ownership, not a complete retry implementation. Fetch API owns basic status, body and decoding rules; this lesson adds bounded retry, delay and cancellation decisions.

let calls = 0;
const reason = new Error("offline");
const work = () => { calls++; return Promise.reject(reason); };
const pending = work();
for (let attempt = 0; attempt < 2; attempt++) {
  try { await pending; } catch (error) { console.log(error === reason); }
}
console.log(calls);

// ✅ Expected output:
// true
// true
// 1

HTTP status, transport failure and decoding failure are different boundaries

const response = new Response('{"message":"busy"}', {
  status: 503, headers: { "Content-Type": "application/json" }
});
console.log(response.ok, response.status);
console.log((await response.json()).message);

// ✅ Expected output:
// false 503
// busy
const response = new Response("not JSON", {
  status: 200, headers: { "Content-Type": "application/json" }
});
try { await response.json(); } catch (error) { console.log(error.name); }
console.log(response.bodyUsed);

// ✅ Expected output:
// SyntaxError
// true

A browser fetch rejection can reflect several conditions, including network and browser-policy failures; its type alone is not a reliable diagnosis. Automatically retrying every TypeError could repeat a programming error, a blocked request or a permanently invalid payload. The brief retries only two chosen HTTP statuses and lets transport/decoding failures propagate. This is a deliberately narrow policy, not a recommendation that every API use these same choices.

Repeating a write can repeat its side effect

let stored = 0, calls = 0;
async function createItem() {
  stored++; calls++;
  if (calls === 1) throw new Error("reply lost after write");
  return { stored };
}
try { await createItem(); } catch {}
const reply = await createItem();
console.log(calls, stored, reply.stored);

// ✅ Expected output:
// 2 2 2

This controlled transport commits before failing its first reply. Repeating it creates a second item. HTTP method semantics matter: GET is intended for retrieval, while blindly retrying an arbitrary POST can duplicate work. A server-supported idempotency key can help only when its scope, persistence and duplicate handling are part of that server’s contract; merely inventing a header does not establish those guarantees.

const request = new Request("https://example.invalid/items", { method: "POST", body: "item" });
const copy = request.clone();
console.log(await request.text(), request.bodyUsed);
try { request.clone(); } catch (error) { console.log(error.name); }
console.log(await copy.text());

// ✅ Expected output:
// item true
// TypeError
// item

Construct fresh per-attempt request state when a legitimate retry requires it. This example only reads local Request objects and sends nothing. Authentication refresh, replayable streams and server-side deduplication are separate designs.

Respect server delay instructions or stop instead of shortening them

function retryDelay(response, attempt) {
  const header = response.headers.get("Retry-After");
  if (header === null) return 100 * 2 ** (attempt - 1);
  const text = header.trim();
  if (!/^\d+$/.test(text)) return null;
  const seconds = Number(text);
  if (!Number.isSafeInteger(seconds) || seconds > 2) return null;
  return seconds * 1000;
}
for (const header of [null, "0", "2", "30", "Thu, 01 Jan 2026 00:00:00 GMT", "bad"]) {
  const response = new Response(null, { status: 503, headers: header === null ? {} : { "Retry-After": header } });
  const delay = retryDelay(response, 1);
  console.log(header === null ? "absent" : header, delay === null ? "stop" : delay);
}

// ✅ Expected output:
// absent 100
// 0 0
// 2 2000
// 30 stop
// Thu, 01 Jan 2026 00:00:00 GMT stop
// bad stop

Retry-After can be delay seconds or an HTTP date. This exercise supports only integer delay seconds up to two; a longer, malformed or date-form value stops automatic retry. It never caps a server’s larger requested wait to a shorter interval. Without the header, the brief uses a small deterministic exponential schedule. These limits keep the exercise bounded; real policy depends on the service and user interaction.

function fullJitter(cap, fraction) {
  if (!Number.isFinite(fraction) || fraction < 0 || fraction >= 1) throw new RangeError("fraction must be in [0, 1)");
  return Math.floor(cap * fraction);
}
console.log([0, 0.25, 0.75].map(value => fullJitter(400, value)).join(","));
try { fullJitter(400, 1); } catch (error) { console.log(error.name, error.message); }

// ✅ Expected output:
// 0,100,300
// RangeError fraction must be in [0, 1)

A fleet of clients repeating identical delays can synchronize retries. Jitter spreads their chosen delays; this fixed-fraction check establishes the calculation without printing random output. The brief keeps its schedule deterministic and does not add jitter below a server-specified minimum.

A timeout race and cooperative cancellation are different mechanisms

let finish;
const trace = [];
const operation = new Promise(resolve => {
  finish = () => { trace.push("operation finished"); resolve("late"); };
});
const timeout = new Error("deadline");
try { await Promise.race([operation, Promise.reject(timeout)]); }
catch (error) { console.log(error === timeout); }
finish();
await operation;
console.log(trace.join(","));

// ✅ Expected output:
// true
// operation finished
const controller = new AbortController();
const reason = new Error("cancelled by caller");
controller.abort(reason);
controller.abort(new Error("replacement"));
console.log(controller.signal.aborted, controller.signal.reason === reason);
try { controller.signal.throwIfAborted(); } catch (error) { console.log(error === reason); }

// ✅ Expected output:
// true true
// true

Pass the signal into work that supports cancellation. Aborting an unrelated controller does not stop a request. A signal cannot be reset for another attempt. A total deadline and a separate per-attempt deadline also have different scopes; retrying must not quietly reset a user’s intended total budget. AbortController & Cancelling Async Work owns signal composition and cancellation APIs.

async function withDeadline(operation, ms, timers, callerSignal) {
  if (typeof operation !== "function") throw new TypeError("operation must be a function");
  if (!Number.isInteger(ms) || ms < 1) throw new RangeError("deadline must be a positive integer");
  const deadline = new AbortController();
  const signal = callerSignal
    ? AbortSignal.any([callerSignal, deadline.signal])
    : deadline.signal;
  signal.throwIfAborted();
  const handle = timers.set(() => deadline.abort(new DOMException("deadline exceeded", "TimeoutError")), ms);
  try {
    const result = await operation(signal);
    signal.throwIfAborted();
    return result;
  } finally {
    timers.clear(handle);
  }
}
let fire, cleared = false;
const timers = {
  set(callback) { fire = callback; return 0; },
  clear(handle) { cleared = handle === 0; fire = null; }
};
const pending = withDeadline(signal => new Promise((resolve, reject) => {
  signal.addEventListener("abort", () => reject(signal.reason), { once: true });
}), 100, timers);
fire();
try { await pending; } catch (error) { console.log(error.name, error.message); }
console.log(cleared, fire === null);
console.log(await withDeadline(async () => 7, 100, timers), cleared, fire === null);

// ✅ Expected output:
// TimeoutError deadline exceeded
// true true
// 7 true true

The operation must cooperate with the supplied signal. Keep response-body reading inside that operation if the deadline is meant to cover it; resolving the operation after headers alone ends the timer too early for that purpose. The finally block cancels the timer after success or failure. This controlled test fires a deadline explicitly and checks cleanup, not elapsed time. A non-cooperating operation can remain pending even after the signal aborts.

function abortableDelay(ms, signal, timers) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) { reject(signal.reason); return; }
    let handle;
    const cleanup = () => signal?.removeEventListener("abort", abort);
    const finish = () => { cleanup(); resolve(); };
    const abort = () => { timers.clear(handle); cleanup(); reject(signal.reason); };
    handle = timers.set(finish, ms);
    signal?.addEventListener("abort", abort, { once: true });
  });
}
let callback = null, cancelled = false;
const timers = {
  set(fn) { callback = fn; return 0; },
  clear(handle) { cancelled = handle === 0; callback = null; }
};
const controller = new AbortController();
const reason = { kind: "leave page" };
const pending = abortableDelay(100, controller.signal, timers);
controller.abort(reason);
try { await pending; } catch (error) { console.log(error === reason); }
console.log(cancelled, callback === null);

// ✅ Expected output:
// true
// true true

The delay removes its listener on fulfillment or abort. The injected timer interface is asynchronous by contract and treats handles as opaque, including zero. A real adapter calls setTimeout and clearTimeout through wrapper functions. A transport or sleeper that ignores its signal can remain pending: a wrapper’s checks cannot forcibly terminate arbitrary promises.

Keep retries separate from concurrency and stale-result ownership

Three attempts in a loop are sequential for that invocation, but ten callers can still start ten such loops. Async/Await Architecture & Best Practices owns bounded concurrent work. Likewise, aborting an old request is not a replacement for deciding which invocation may publish a result; Advanced Scope, Closures & Lexical Environments owns that publication rule.

Avoid logging full authorization headers, secret query strings or response bodies by default. A retry report can expose an attempt number and category without copying sensitive payloads. The brief returns decoded JSON as unknown application data; a caller must still validate its expected shape.

Guided exercise: stop retrying a terminal status

Complete the literal hints. Use fresh responses, consume success once, retry only 503 while another attempt remains, and report a terminal status.

const statuses = [503, 404, 200];
let calls = 0;
for (let attempt = 1; attempt <= 3; attempt++) {
  const response = new Response(null, { status: statuses[calls++] });
  if (response.___) break; // 👉 replace ___ with ok
  if (response.status === ___ && attempt < 3) continue; // 👉 replace ___ with 503
  console.log("stop", response.status);
  ___; // 👉 replace ___ with break
}
console.log(calls);

// ✅ Expected output:
// stop 404
// 2

Independent brief: a bounded GET JSON retry helper

Implement readJsonWithRetries(url, options) using injected transport and sleep functions, attempts from one through three, and an optional AbortSignal. Always request GET. Check cancellation before attempts, after transport, after sleeping and after JSON decoding. Accept only successful application/json responses; propagate transport and decoding failures unchanged. Retry only 429 or 503 while attempts remain.

For missing Retry-After, wait 100 then 200 milliseconds. Support non-negative integer delay seconds up to two; stop on larger or unsupported values instead of retrying too early. Cancel discarded response bodies. Throw an HTTPError with status and attempt for terminal HTTP outcomes. Tests use fresh real Response fixtures and a recorded sleeper, so there is no network or waiting-time claim. This helper has no total deadline, credentials policy, schema validator or unsafe-method retry feature.

function retryDelay(response, attempt) {
  const header = response.headers.get("Retry-After");
  if (header === null) return 100 * 2 ** (attempt - 1);
  const text = header.trim();
  if (!/^\d+$/.test(text)) return null;
  const seconds = Number(text);
  if (!Number.isSafeInteger(seconds) || seconds > 2) return null;
  return seconds * 1000;
}
async function readJsonWithRetries(url, { transport, sleep, attempts = 3, signal } = {}) {
  if (typeof url !== "string" || url === "") throw new TypeError("url must be a non-empty string");
  if (typeof transport !== "function" || typeof sleep !== "function") throw new TypeError("transport and sleep must be functions");
  if (!Number.isInteger(attempts) || attempts < 1 || attempts > 3) throw new RangeError("attempts must be from 1 to 3");
  for (let attempt = 1; attempt <= attempts; attempt++) {
    signal?.throwIfAborted();
    const response = await transport(url, { method: "GET", signal });
    signal?.throwIfAborted();
    if (!(response instanceof Response)) throw new TypeError("transport must return a Response");
    if (response.ok) {
      const mediaType = (response.headers.get("Content-Type") ?? "").split(";")[0].trim().toLowerCase();
      if (mediaType !== "application/json") {
        await response.body?.cancel();
        throw new TypeError("response must have application/json content");
      }
      const value = await response.json();
      signal?.throwIfAborted();
      return value;
    }
    const canRetry = (response.status === 429 || response.status === 503) && attempt < attempts;
    const delay = canRetry ? retryDelay(response, attempt) : null;
    const status = response.status;
    await response.body?.cancel();
    if (delay === null) {
      const error = new Error("HTTP " + status);
      error.name = "HTTPError"; error.status = status; error.attempt = attempt;
      throw error;
    }
    await sleep(delay, signal);
    signal?.throwIfAborted();
  }
}
function scripted(statuses, headers = {}) {
  const seen = [];
  return {
    seen,
    async transport(url, options) {
      seen.push(options.method);
      const status = statuses.shift();
      return new Response('{"value":7}', { status, headers: { "Content-Type": "application/json", ...headers } });
    }
  };
}
const first = scripted([503, 429, 200]);
const waits = [];
const value = await readJsonWithRetries("offline-fixture", { transport: first.transport, sleep: async ms => waits.push(ms) });
console.log(value.value, first.seen.join(","), waits.join(","));
const limited = scripted([503, 200], { "Retry-After": "30" });
try { await readJsonWithRetries("offline-fixture", { transport: limited.transport, sleep: async () => {} }); }
catch (error) { console.log(error.name, error.status, error.attempt, limited.seen.length); }
const terminal = scripted([404, 200]);
try { await readJsonWithRetries("offline-fixture", { transport: terminal.transport, sleep: async () => {} }); }
catch (error) { console.log(error.name, error.status, terminal.seen.length); }
const controller = new AbortController(), reason = { cancelled: true };
const cancelling = scripted([503, 200]);
try {
  await readJsonWithRetries("offline-fixture", {
    transport: cancelling.transport, signal: controller.signal,
    sleep: async () => controller.abort(reason)
  });
} catch (error) { console.log(error === reason, cancelling.seen.length); }
const exhausted = scripted([503, 503, 503]);
try { await readJsonWithRetries("offline-fixture", { transport: exhausted.transport, sleep: async () => {} }); }
catch (error) { console.log(error.name, error.attempt, exhausted.seen.length); }
const invalidJSON = async () => new Response("broken", { headers: { "Content-Type": "application/json" } });
try { await readJsonWithRetries("offline-fixture", { transport: invalidJSON, sleep: async () => {} }); }
catch (error) { console.log(error.name); }

// ✅ Expected output:
// 7 GET,GET,GET 100,200
// HTTPError 503 1 1
// HTTPError 404 1
// true 1
// HTTPError 3 3
// SyntaxError

Reference notes

The Fetch guide distinguishes response status and body consumption. The Retry-After reference defines its forms, and AbortSignal documents one-shot cancellation and reasons. All fixtures here are offline; successful fixture runs do not verify a remote endpoint.

Practice quiz

What does this complete program print? let calls=0;const work=()=>{calls++;return Promise.resolve("ok")};const pending=work();await pending;await pending;console.log(calls);

  • 1
  • 0
  • 2
  • undefined

Answer: 1. Observing a promise twice does not invoke its producer twice.

What does this complete program print? const response=new Response(null,{status:503});console.log(response.ok,response.status);

  • true 503
  • false 503
  • false 200
  • true 200

Answer: false 503. An HTTP error status can be represented by a fulfilled Response.

What does this complete program print? const controller=new AbortController();const reason={id:1};controller.abort(reason);controller.abort({id:2});console.log(controller.signal.reason===reason);

  • false
  • undefined
  • true
  • TypeError

Answer: true. The first abort reason is retained.

What does this complete program print? const response=new Response("broken",{headers:{"Content-Type":"application/json"}});try{await response.json()}catch(error){console.log(error.name)}

  • TypeError
  • HTTPError
  • undefined
  • SyntaxError

Answer: SyntaxError. A JSON media type does not guarantee valid JSON syntax.

What does this complete program print? const status=404,attempt=1,max=3;console.log((status===429||status===503)&&attempt<max);

  • false
  • true
  • undefined
  • TypeError

Answer: false. This explicit policy treats 404 as terminal.

What does this complete program print? const delays=[];for(let attempt=1;attempt<3;attempt++)delays.push(100*2**(attempt-1));console.log(delays.join(","));

  • 100,100
  • 100,200
  • 200,400
  • 100,200,400

Answer: 100,200. Three total attempts have only two intervening delays.

What does this complete program print? const response=new Response("A");const clone=response.clone();console.log(await response.text(),await clone.text());

  • A undefined
  • undefined A
  • A A
  • TypeError

Answer: A A. Cloning before consumption provides separately consumable bodies.

What does this complete program print? let complete;const trace=[];const work=new Promise(resolve=>{complete=()=>{trace.push("finished");resolve()}});try{await Promise.race([work,Promise.reject("timeout")])}catch{}complete();await work;console.log(trace.join(","));

  • timeout
  • undefined
  • cancelled
  • finished

Answer: finished. A promise race alone does not cancel the losing operation.

Continue this course

Related lessons