Thuta Learning
JavaScript
ProjectsProgrammingBeginner

API Dashboard

JavaScriptLesson 4945 min

What you'll walk away with

  • Keep network code in one request() function that throws an HttpError on bad statuses
  • Choose between sequential awaits, Promise.all() and Promise.allSettled()
  • Validate response data before aggregating it
  • Ignore obsolete responses with a request-ID guard

Explain it simply

Explain it simply

A dashboard is like the instrument panel in a car. Speed, fuel and temperature each come from their own sensor. If the fuel sensor fails, the car does not switch off every gauge; the fuel gauge shows a warning light and the rest keep working.

An API Dashboard works the same way. The users, posts and stats endpoints each feed one panel. The app sends the requests at the same time, checks the data that comes back, computes the numbers and only then displays them. If one panel fails, only that panel shows an error.

Problem → Why → Solution

The problem: a dashboard that is slow and fragile

The draft below writes three awaits one after another. If each endpoint takes 300ms, the dashboard appears after 900ms. The requests do not depend on each other, yet they wait in a queue.

When the stats endpoint returns a 500, the error JSON is parsed anyway, stats.totalViews is undefined, and toLocaleString() throws a TypeError. The users and posts data were fine, but the whole page stays blank. Because toLocaleString() is called without a locale, 1250 prints as "1,250" on an English machine and "1.250" on a German one. And if the filter changes twice quickly, the slower first request can arrive last and cover the newer result.

dashboard-draft.js
async function loadDashboard() {
  const users = await fetch("/api/users").then((r) => r.json()); // wait...
  const posts = await fetch("/api/posts").then((r) => r.json()); // ...wait again
  const stats = await fetch("/api/stats").then((r) => r.json()); // a 500? parsed anyway
  panel.innerHTML = `Users: ${users.length}, posts: ${posts.length},
    views: ${stats.totalViews.toLocaleString()}`; // "1.250" on a German PC
}

// Two quick filter changes: the older, slower reply may be drawn last.
filterSelect.addEventListener("change", loadDashboard);

The root cause

Network access, data checks, calculation and drawing are mixed in one function, and none of the failure points were planned for. Treating three requests as one all-or-nothing group does not match a dashboard, where each panel should be able to fail on its own.

Core concept: five layers and settled requests

Think of an API-driven app as five layers. Each layer has one job and only calls the layer below it. With that split, when a bug appears you know immediately which layer to look in.

  • Transport: request() calls the URL and throws an HttpError carrying the status for anything outside 200-299. Timeouts and headers live here too.
  • Validation: checks that the data has the expected shape. If an object arrives where an array should be, the problem stops here.
  • Aggregation: pure functions turn raw data into the numbers on screen.
  • State: remembers what the dashboard currently shows: loading, data, or a panel error.
  • Rendering: draws from the state and never calls the network directly.

How you wait for the requests is a decision too. Await them one after another only when a request needs the previous one's result. Start independent requests together and wait with Promise.all() or Promise.allSettled().

ApproachTotal waitWhen one fails
One await after anotherSum of all requestsThe rest never start
Promise.all()The slowest requestRejects at once; all results lost
Promise.allSettled()The slowest requestReports each one as fulfilled or rejected

For a dashboard, allSettled() is usually the better fit, but not every panel is equal. Without users and posts the dashboard means nothing, so it reports "unavailable"; if only stats fails, everything else renders and just the stats panel shows the error.

Layers make testing cheap

summarize() takes two arrays and returns an object, a pure function you can test with no server, promise or timer. Swap request() for a fake and you can try a 500, a 404 and malformed JSON in seconds. In code where the layers are mixed, testing each of those cases would mean actually breaking a real server. That is why this lesson's whole example runs without any network at all.

Mental model: one sensor, one gauge
  1. Start every request at once
  2. Wait for each with allSettled()
  3. Validate and compute fulfilled data
  4. Each panel shows data or its error

If core data (users, posts) fails, the whole dashboard is unavailable; if an optional panel (stats) fails, only that panel is affected.

General pattern

javascript
const results = await Promise.allSettled([
  request("/api/first"),
  request("/api/second"),
]);

for (const result of results) {
  if (result.status === "fulfilled") render(result.value);
  else renderPanelError(result.reason); // one panel fails, the rest still show
}

Start the requests together in one array; allSettled() returns each outcome as { status, value } or { status, reason }, and you handle every outcome separately.

The dashboard with stats failing, then healthy

The fakeServer object defines a status and a body for each path. In the first run /api/stats returns a 500; before the second run it is repaired. In the output, notice that the users and posts panels appear both times and only the stats panel changes.

dashboard.js
// dashboard.js - transport, validation, aggregation and text rendering. No DOM.
const fakeServer = {
  "/api/users": { status: 200, body: [
    { id: 1, name: "Aung Kyaw", active: true },
    { id: 2, name: "Su Su", active: true },
    { id: 3, name: "Min Min", active: false },
  ] },
  "/api/posts": { status: 200, body: [
    { id: 1, userId: 1, likes: 10 },
    { id: 2, userId: 1, likes: 5 },
    { id: 3, userId: 2, likes: 15 },
  ] },
  "/api/stats": { status: 500, body: { error: "database timeout" } },
};

class HttpError extends Error {
  constructor(status, path) {
    super(`HTTP ${status} from ${path}`);
    this.status = status;
  }
}

// Transport: one place that talks to the network (faked here).
async function request(path) {
  const route = fakeServer[path] ?? { status: 404, body: null };
  await new Promise((resolve) => setTimeout(resolve, 10));
  if (route.status < 200 || route.status > 299) throw new HttpError(route.status, path);
  return route.body;
}

// Validation: refuse data the rest of the code cannot handle.
function expectArray(value, name) {
  if (!Array.isArray(value)) throw new TypeError(`${name} should be an array`);
  return value;
}

// Aggregation: pure functions from raw data to the numbers on screen.
function summarize(users, posts) {
  const active = users.filter((u) => u.active).length;
  const likes = posts.reduce((sum, p) => sum + p.likes, 0);
  const avg = posts.length ? likes / posts.length : 0;
  return { users: users.length, active, posts: posts.length, likes, avg };
}

async function loadDashboard() {
  const [users, posts, stats] = await Promise.allSettled([
    request("/api/users").then((d) => expectArray(d, "users")),
    request("/api/posts").then((d) => expectArray(d, "posts")),
    request("/api/stats"),
  ]);
  if (users.status === "rejected" || posts.status === "rejected") {
    return ["Dashboard unavailable: core data failed to load"];
  }
  const s = summarize(users.value, posts.value);
  const lines = [
    `Users: ${s.users} (${s.active} active, ${s.users - s.active} inactive)`,
    `Posts: ${s.posts}, likes: ${s.likes}, avg: ${s.avg.toFixed(1)}`,
  ];
  if (stats.status === "fulfilled") {
    lines.push(`Views: ${stats.value.totalViews.toLocaleString("en-US")}`);
  } else {
    lines.push(`Stats panel: unavailable (${stats.reason.message})`);
  }
  return lines;
}

console.log("-- stats endpoint failing --");
(await loadDashboard()).forEach((line) => console.log(line));

fakeServer["/api/stats"] = { status: 200, body: { totalViews: 1250 } };
console.log("-- all endpoints healthy --");
(await loadDashboard()).forEach((line) => console.log(line));

Code breakdown

  1. An error that carries the statusclass HttpError extends Error {

    Extending Error lets the status travel as a property, so the UI can send a 401 to the login page and show "try again later" for a 500.

  2. Validate before you computerequest("/api/users").then((d) => expectArray(d, "users")),

    If the server sends an object instead of an array, this stops with a clear "users should be an array" before summarize() can fail with a puzzling "filter is not a function".

  3. All three start togetherconst [users, posts, stats] = await Promise.allSettled([

    All three requests start immediately and allSettled() waits until every one has settled. No single rejection throws the other results away.

  4. Core data versus optional panelsif (users.status === "rejected" || posts.status === "rejected") {

    Users and posts are core data, so if either fails the whole dashboard reports unavailable. Stats is deliberately left out of this condition, so its failure affects only its own panel.

  5. A fixed locale for numbersstats.value.totalViews.toLocaleString("en-US")

    Passing the locale explicitly makes this print "1,250" on every machine. If you want the user's own locale instead, your tests must pin the locale they run with.

You should see
-- stats endpoint failing --
Users: 3 (2 active, 1 inactive)
Posts: 3, likes: 30, avg: 10.0
Stats panel: unavailable (HTTP 500 from /api/stats)
-- all endpoints healthy --
Users: 3 (2 active, 1 inactive)
Posts: 3, likes: 30, avg: 10.0
Views: 1,250

The real transport for the browser

The request() in the example calls a fake server, but the browser version keeps exactly the same contract: take a path, throw an HttpError on a bad status, otherwise return the parsed JSON. Because the layers are separate, swapping this one function requires no change at all to the validation, aggregation or rendering code.

AbortSignal.timeout() cancels the request once the time runs out and rejects with a TimeoutError. Without a timeout, a server that never answers leaves the loading spinner turning forever.

api.js
// api.js - the browser version of request(): same contract, real network
async function request(path, { timeoutMs = 8000 } = {}) {
  const res = await fetch(path, {
    headers: { Accept: "application/json" },
    signal: AbortSignal.timeout(timeoutMs), // give up on a server that hangs
  });
  if (!res.ok) throw new HttpError(res.status, path);
  return res.json();
}

In real projects

In real projects

Admin panels, analytics pages and monitoring screens use this pattern every day. Teams keep request() as one API client for the whole project and handle auth tokens, timeouts and retries in that single place.

Give each status code a meaningful response. A 401 means the session expired, so ask the user to log in again. A 404 means the data does not exist. A 409 means someone else changed it first, so offer a reload. A 500 or 503 can be retried after a short pause. Tests should cover more than the happy path: use the fake server to try slow responses, malformed JSON, a 401, a 500, and responses arriving in reverse order.

Common mistakes

Common mistakes

Using Promise.all() where partial failure is normal

Promise.all() rejects as soon as one promise rejects and never hands back the results that succeeded. One optional panel turns the whole dashboard into an error screen. When panels should be independent, use allSettled().

Awaiting independent requests one by one

With const a = await getA(); const b = await getB(); the second request starts only after the first finishes. Start independent requests together in an array, then wait. A staircase of requests in the Network tab is the tell-tale sign of this mistake.

Letting an old response overwrite new state

When each filter change sends a new request, nothing guarantees the responses return in the order they were sent. Give every request an ID and apply only the latest ID's result, or cancel the old one with an AbortController.

Mini challenge

Build a latest-only guard

Write createLatestOnly(), which wraps an async function and marks only the most recent call's result as fresh. Simulate fast typing with a fake search whose delays differ per term, and show that stale results never reach the screen.

  • Each call takes its own ID from a counter
  • Results come back as { stale, value }
  • An error from a stale call returns { stale: true, error } instead of throwing
  • An error from the latest call is re-thrown so the user sees it
latest-only.js
function createLatestOnly(asyncFn) {
  // TODO: keep a counter of how many calls have started
  return async (...args) => {
    // TODO: give this call its own id from the counter
    // TODO: await asyncFn(...args) and return { stale, value }
    //       where stale is true when a newer call has started since
    // TODO: if it throws and is stale, return { stale: true, error } instead;
    //       if it throws and is still the latest, re-throw
  };
}

// TODO: a fakeSearch(term) that resolves after a per-term delay (setTimeout)
// TODO: onType(term) that applies fresh results and logs ignored stale ones
// TODO: start "s" (slow) and "su" (fast) together with Promise.all

Expected: "su" is applied and "s" is ignored as stale; "min" is applied and the "zz" error is ignored; only the final lone "zz" call shows an error, and the screen still shows Min Min.

Show hint

Keep let latest = 0 outside the wrapper and do const id = ++latest on every call. After the await, id !== latest means a newer call started in the meantime.

Show solution
latest-only.js
function createLatestOnly(asyncFn) {
  let latest = 0;
  return async (...args) => {
    const id = ++latest; // this call's ticket number
    try {
      const value = await asyncFn(...args);
      return { stale: id !== latest, value };
    } catch (error) {
      if (id !== latest) return { stale: true, error }; // nobody waits for it
      throw error;
    }
  };
}

// Fake API: each term answers after its own delay, like a real network.
const people = ["Su Su", "Aung Kyaw", "Min Min", "Su Myat"];
const delays = { s: 120, su: 20, zz: 80, min: 10 };

function fakeSearch(term) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (term === "zz") reject(new Error("HTTP 500"));
      else resolve(people.filter((p) => p.toLowerCase().includes(term)));
    }, delays[term]);
  });
}

const search = createLatestOnly(fakeSearch);
const screen = { results: [] };

async function onType(term) {
  try {
    const outcome = await search(term);
    if (outcome.stale) return console.log(`ignored stale "${term}"`);
    screen.results = outcome.value;
    console.log(`applied "${term}": ${screen.results.join(", ")}`);
  } catch (error) {
    console.log(`error for "${term}": ${error.message}`);
  }
}

// The user types "s" then "su"; the slower "s" answer arrives last.
await Promise.all([onType("s"), onType("su")]);
// A failing request that is already obsolete must not show an error.
await Promise.all([onType("zz"), onType("min")]);
// A failing request that is still the latest must show its error.
await onType("zz");
console.log("screen shows:", screen.results.join(", "));

Quick quiz 1 / 3

Three requests are awaited with Promise.all() and the second one rejects. What happens to the first and third results?

Quick quiz 2 / 3

In the example, what does loadDashboard() return if /api/posts answers with a 500?

Quick quiz 3 / 3

A user switches the filter from A to B quickly, and A's request is slower than B's. Without a guard, what ends up on screen?

What to remember

  • Split an API app into transport, validation, aggregation, state and rendering
  • Check the status in a single request() and pass it along in an HttpError
  • Start independent requests together; use allSettled() when panels are independent
  • Call toLocaleString() with an explicit locale
  • Ignore obsolete responses with a request-ID guard

MDN — Fetch API — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

API Dashboard | Thuta Learning