Back to the blog

Tony CantaveFetching Data in JavaScript with async and await: Timeouts, Errors and Retries

By Tony Cantave ·

Almost every JavaScript project I touch ends up calling an API. The screen management software I am building has to pull its content from a server, and a lot of the JavaScript samples I write and debug for AI model training do the same thing. The first version of that code is usually one line with fetch and await, and it works fine on a good day. The trouble shows up on a bad day: a server that never answers, a 500 error that looks like success, or a brief network drop that kills the whole run. Here is the pattern I now start with, piece by piece.

Problem one: fetch does not fail on HTTP errors

This surprises people. fetch only rejects when the request cannot be made at all, such as a network failure. A 404 or a 500 still resolves normally. If you go straight to response.json(), you either parse an error page or get a confusing parse error later.

The fix is to check response.ok every time, and to throw an error that carries the status code so later code can make decisions with it:

class HttpError extends Error {
  constructor(status, url) {
    super(`HTTP ${status} for ${url}`);
    this.name = "HttpError";
    this.status = status;
  }
}

Problem two: fetch has no timeout by default

If the server accepts the connection and then goes quiet, an awaited fetch can hang for a very long time. In a script, that looks like a frozen job. On a screen in a shop, that looks like content that never updates.

AbortController lets you cancel a request yourself. Start a timer, abort when it fires, and always clear the timer when you are done:

async function fetchJson(url, { timeoutMs = 8000 } = {}) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const response = await fetch(url, { signal: controller.signal });
    if (!response.ok) {
      throw new HttpError(response.status, url);
    }
    return await response.json();
  } finally {
    clearTimeout(timer);
  }
}

Two details matter here. The finally block clears the timer whether the request worked or not, so you do not leave stray timers running. And the code uses return await inside the try. Without the await, a rejected promise from response.json() would skip this function's error handling entirely, which is an easy bug to miss in review. Modern browsers and recent Node versions also have AbortSignal.timeout, which does the same job in one line if your runtime supports it.

Problem three: retrying everything makes things worse

Once errors are visible, the next temptation is to wrap the call in a loop and retry until it works. That is how you end up hammering a server that is already struggling, or retrying a 401 that will never succeed.

I sort errors into two groups. Worth retrying: a timeout, a network failure, a 429 (too many requests) and any 5xx server error. Not worth retrying: other 4xx errors, because the request itself is wrong, and JSON parse errors, because the response will not fix itself.

function isRetryable(error) {
  if (error.name === "AbortError") return true; // our timeout fired
  if (error.name === "TypeError") return true;  // network failure
  if (error instanceof HttpError) {
    return error.status === 429 || error.status >= 500;
  }
  return false;
}

Then the retry wrapper waits a little longer after each failure, so a busy server gets room to recover:

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function fetchWithRetry(url, { attempts = 3, delayMs = 500 } = {}) {
  let delay = delayMs;

  for (let attempt = 1; attempt <= attempts; attempt += 1) {
    try {
      return await fetchJson(url);
    } catch (error) {
      const lastTry = attempt === attempts;
      if (lastTry || !isRetryable(error)) {
        throw error;
      }
      console.warn(`Attempt ${attempt} failed (${error.message}), waiting ${delay} ms`);
      await sleep(delay);
      delay *= 2;
    }
  }
}

Three attempts with a delay that doubles is plenty for most small jobs. The log line is not optional for me. When something fails at night, the first question is whether it failed once and recovered or failed every time, and that line answers it.

Problem four: one bad source should not sink the rest

When a page or a job needs data from several endpoints, Promise.all is the usual choice, but it rejects as soon as any single request fails. Often I would rather keep what worked and report what did not. Promise.allSettled does exactly that:

const urls = [
  "https://api.example.com/playlist",
  "https://api.example.com/schedule",
  "https://api.example.com/settings",
];

const results = await Promise.allSettled(urls.map((url) => fetchWithRetry(url)));

results.forEach((result, index) => {
  if (result.status === "fulfilled") {
    console.log("OK", urls[index]);
  } else {
    console.error("FAILED", urls[index], result.reason.message);
  }
});

For screen content specifically, this is the difference between showing slightly old settings and showing nothing at all. The code can fall back to the last good copy for the one source that failed.

Check the shape before you trust it

A 200 response with valid JSON can still be the wrong data. Before using it, I check the fields the rest of the code depends on:

function assertPlaylist(data) {
  if (!Array.isArray(data.items)) {
    throw new Error("Playlist response is missing an items array");
  }
  return data;
}

It is a few lines, and it turns a strange crash three functions later into a clear message at the point where the data came in.

What I take from this

Years of running delivery and production operations taught me to plan for the day the truck is late, not the day everything goes right. Network code is the same. Check response.ok, put a timeout on every request, retry only what can actually succeed on a second try, keep partial results when you can, and verify the data before you use it. None of it is complicated, and all of it is cheaper than finding out the hard way.