Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 2

Lab: Search-as-You-Type Against a Public API

Build a search client that debounces input, aborts stale requests, and shows loading, empty, error and retry states — driven by a scripted typing session.

Contentsand lesson path

What you will learn

  • Write promise-based code with async/await, running independent requests in parallel with Promise.all or Promise.allSettled and handling every rejection.
  • Call a JSON HTTP API with fetch: check response.ok, distinguish HTTP errors from network failures, parse the body, and send JSON with the correct method and headers.
  • Cancel or ignore stale requests with AbortController and show loading, empty, error and retry states to the user.

Prerequisites: JavaScript Foundations

01. Goal and setup

This lab assembles the three previous lessons into the skill's practice project: a client that searches a JSON API as the user types. It debounces the input, aborts requests the query has left behind, tells HTTP errors from network failures, and shows four honest states — loading, empty, error with retry, and results. Every step prints the state transitions, so you can watch the client behave instead of imagining it.

The target is a "public-style" search API: GET /search?q=... returning a JSON array. Real public APIs vary in shape but not in behaviour — they are slow, sometimes fail, and never promise ordered replies. So the lab runs a stand-in API on your own machine whose quirks are deterministic: every request waits 350 ms, and the first request whose query contains an x fails with a 500 (once per server start, so retry has something to fix). The apply step at the end points the finished client at a real public API.

You need: Node.js 22 or later (node --version; the outputs below were captured on 22.23, and 26 is the current Active LTS) and a terminal. Nothing to install: the lab uses only built-in modules. The layout:

Project layout
search-lab/
├── api.mjs       the stand-in API (port 4200)
└── client.mjs    the client, rewritten at each step

02. Step 1: stand up the API

JavaScript · api.mjs
import { createServer } from 'node:http';

const catalogue = [
  { title: 'Eloquent JavaScript', author: 'Marijn Haverbeke' },
  { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford' },
  { title: "You Don't Know JS Yet", author: 'Kyle Simpson' },
  { title: 'Effective TypeScript', author: 'Dan Vanderkam' },
  { title: 'CSS Secrets', author: 'Lea Verou' },
  { title: 'Refactoring UI', author: 'Adam Wathan and Steve Schoger' },
];

const LATENCY_MS = 350;
let firstXFailureDone = false;

createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  if (url.pathname !== '/search') {
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'unknown path' }));
    return;
  }
  const q = (url.searchParams.get('q') ?? '').trim().toLowerCase();
  setTimeout(() => {
    if (q.includes('x') && !firstXFailureDone) {
      firstXFailureDone = true; // one simulated fault per server start
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: 'internal server error (simulated)' }));
      return;
    }
    const matches = catalogue.filter((book) =>
      `${book.title} ${book.author}`.toLowerCase().includes(q),
    );
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(matches));
  }, LATENCY_MS);
}).listen(4200, () => console.log("stand-in API on http://localhost:4200"));
Terminal
node api.mjs
curl -s 'http://localhost:4200/search?q=css'
Expected output
stand-in API on http://localhost:4200
[{"title":"CSS Secrets","author":"Lea Verou"}]

Keep this server running in its own terminal. Two habits matter for the rest of the lab. First, restart the server before each client run (Ctrl-C, then up-arrow and Enter): the simulated 500 is armed once per start, and the client exercises it in every step. Second, every query is matched against title + author lower-cased, so j matches three books and js exactly one — useful for telling responses apart.

03. Step 2: the naive client — three bugs in nine lines

JavaScript · client.mjs
import { setTimeout as delay } from 'node:timers/promises';

const BASE = 'http://localhost:4200/search';

function show(query, body) {
  if (Array.isArray(body)) {
    console.log(`results for "${query}" (${body.length}):`);
    for (const book of body) console.log(`  - ${book.title}`);
  } else {
    console.log(`results for "${query}":`, JSON.stringify(body));
  }
}

async function onKey(query) {
  const res = await fetch(`${BASE}?q=${encodeURIComponent(query)}`);
  show(query, await res.json()); // bug: never checks res.ok
}

// The user types "jsx": j at t=0, s at t=90, x at t=380
await delay(0); onKey('j');
await delay(90); onKey('js');
await delay(290); onKey('jsx');
await delay(600); // let every request finish
Expected output
results for "j" (3):
  - Eloquent JavaScript
  - JavaScript: The Good Parts
  - You Don't Know JS Yet
results for "js" (1):
  - You Don't Know JS Yet
results for "jsx": {"error":"internal server error (simulated)"}

One typed word, three requests — the client asks on every keystroke. The last line is the loudest bug: the server answered 500 with a JSON error body, fetch resolved as usual, and the client rendered the error object as if it were results. The other two you cannot see in this fixed-latency log but lesson 4 demonstrated them: responses can arrive out of send order, and nothing here would notice. Sequenced await delay() calls with per-key pauses simulate the user; in a browser the same onKey would be the input handler.

04. Step 3: check res.ok before trusting the body

JavaScript · client.mjs — replace onKey
async function onKey(query) {
  const res = await fetch(`${BASE}?q=${encodeURIComponent(query)}`);
  if (!res.ok) {
    console.log(`error for "${query}": HTTP ${res.status} ${res.statusText}`);
    return;
  }
  show(query, await res.json());
}
Expected output (after restarting the API)
results for "j" (3):
  - Eloquent JavaScript
  - JavaScript: The Good Parts
  - You Don't Know JS Yet
results for "js" (1):
  - You Don't Know JS Yet
error for "jsx": HTTP 500 Internal Server Error

The failure is now named for what it is. res.ok is false for the 500, and the branch reports the status class — a distinction the naive version collapsed. What is still missing: the request fires per keystroke, a stale response could still overwrite a newer one, and the interface cannot tell "working on it" from "broken". Those are steps 4 and 5.

05. Step 4: cancel the query you left behind

JavaScript · client.mjs — controller and new onKey
let controller = null;

function setState(state, query, matches) {
  if (state === "results") {
    console.log(`state: results for "${query}" (${matches.length}):`);
    for (const book of matches) console.log(`  - ${book.title}`);
  } else {
    console.log(`state: ${state} (query "${query}")`);
  }
}

async function onKey(query) {
  controller?.abort(); // a newer keystroke cancels the older request
  controller = new AbortController();
  setState('loading', query);
  try {
    const res = await fetch(`${BASE}?q=${encodeURIComponent(query)}`, {
      signal: controller.signal,
    });
    if (!res.ok) {
      console.log(`state: error for "${query}": HTTP ${res.status} ${res.statusText}`);
      return;
    }
    setState('results', query, await res.json());
  } catch (err) {
    if (err.name === 'AbortError')
      console.log(`request for "${query}" aborted (query changed)`);
    else console.log(`state: error for "${query}": ${err.message}`);
  }
}
JavaScript · client.mjs — the short typing script
await delay(0); onKey('j');
await delay(90); onKey('js');
await delay(600);
Terminal
node client.mjs
Expected output (after restarting the API)
state: loading (query "j")
state: loading (query "js")
request for "j" aborted (query changed)
state: results for "js" (1):
  - You Don't Know JS Yet

Read the order carefully: the second loading prints before the abort message, because abort() rejects the older fetch on a later microtask — the same scheduling rule as lesson 1. The j response never renders; it was cancelled the moment the query moved on. Note also that the error state is formatted with consistent state: logging alongside the other states: from here on, everything the client says follows consistent state prefixes, which is what makes the states auditable. Try it, then check the savings: without abort, the j request would have run to completion for nothing. Before you run step 5, which drops the abort and adds a debounce, predict on paper: can a response for an old query still reach the screen?

06. Step 5: debounce — and why abort alone is not enough

JavaScript · client.mjs — replaces everything below BASE with debounced input
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

async function runSearch(query) {
  console.log(`state: loading (query "${query}")`);
  const res = await fetch(`${BASE}?q=${encodeURIComponent(query)}`);
  if (!res.ok) {
    console.log(`state: error for "${query}": HTTP ${res.status} ${res.statusText}`);
    return;
  }
  const matches = await res.json();
  console.log(`state: results for "${query}" (${matches.length}):`);
  for (const book of matches) console.log(`  - ${book.title}`);
}

const onKey = debounce(runSearch, 150);

// j at t=0, s at t=90, x at t=380 (a pause, then typing resumes)
await delay(0); onKey('j');
await delay(90); onKey('js');
await delay(290); onKey('jsx');
await delay(700);
Expected output (after restarting the API)
state: loading (query "js")
state: loading (query "jsx")
state: results for "js" (1):
  - You Don't Know JS Yet
state: error for "jsx": HTTP 500 Internal Server Error

One request per pause now: js fired 150 ms after the last key, jsx after the next pause. But look at the middle line. The js request was still in flight when jsx fired — 350 ms latency beats a 150 ms debounce — and with no abort, its response arrived and rendered for a query that no longer existed. Debounce reduces the number of races; it does not remove them. The final client keeps both tools.

07. Step 6: the full client — four states and a retry

JavaScript · client.mjs — the search core
import { setTimeout as delay } from 'node:timers/promises';

const BASE = 'http://localhost:4200/search';

function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

let controller = null;

function setState(state, query, detail) {
  if (state === "results") {
    console.log(`state: results for "${query}" (${detail.length}):`);
    for (const book of detail) console.log(`  - ${book.title}`);
  } else if (state === "empty") {
    console.log(`state: empty for "${query}": no matches`);
  } else if (state === "error") {
    console.log(`state: error for "${query}": ${detail}`);
  } else {
    console.log(`state: ${state} (query "${query}")`);
  }
}

async function runSearch(query) {
  controller?.abort(); // cancel any request still in flight
  controller = new AbortController();
  setState('loading', query);
  try {
    const res = await fetch(`${BASE}?q=${encodeURIComponent(query)}`, {
      signal: controller.signal,
    });
    if (!res.ok) {
      setState("error", query, `HTTP ${res.status} ${res.statusText}`);
      return;
    }
    const found = await res.json();
    if (found.length === 0) setState('empty', query);
    else setState('results', query, found);
  } catch (err) {
    if (err.name === 'AbortError') {
      console.log(`request for "${query}" aborted (a newer query took over)`);
    } else {
      setState("error", query, err.message); // network failure
    }
  }
}
JavaScript · client.mjs — the scripted session
const onKey = debounce(runSearch, 150);
let query = '';

async function typeKeys(keys) {
  for (const [key, waitBefore] of keys) {
    await delay(waitBefore);
    query += key;
    console.log(`key "${key}" (query "${query}")`);
    onKey(query);
  }
}

// word one: j and s typed quickly, then a pause, then x
await typeKeys([['j', 0], ['s', 90], ['x', 290]]);
await delay(700); // watch the simulated failure arrive
console.log('[retry button clicked]');
await runSearch(query);
console.log('[user clears the box]');
query = '';
await typeKeys([['c', 0], ['s', 90], ['s', 90]]);
await delay(600);
Expected output (after restarting the API)
key "j" (query "j")
key "s" (query "js")
state: loading (query "js")
key "x" (query "jsx")
state: loading (query "jsx")
request for "js" aborted (a newer query took over)
state: error for "jsx": HTTP 500 Internal Server Error
[retry button clicked]
state: loading (query "jsx")
state: empty for "jsx": no matches
[user clears the box]
key "c" (query "c")
key "s" (query "cs")
key "s" (query "css")
state: loading (query "css")
state: results for "css" (1):
  - CSS Secrets

The whole feature in one transcript. js loads; jsx cancels it mid-flight and takes over; the simulated 500 becomes an error state; retry re-runs the same runSearch and gets an honest empty (nothing matches jsx); and the final word lands in results. The keys the debounce swallowed (j, c, cs) never became requests, and no state was ever set from a stale response. Replace setState with DOM updates and typeKeys with an input listener, and this is the search box of a real application.

08. Troubleshooting

09. Check your understanding

Practice check · 3 questions

Why the client is built this way

Justify the design from the transcripts you have seen.

Q1. In runSearch, `setState("loading", query)` runs before `await fetch`. Why does the position matter?
Q2. In the step 4 transcript, the second `loading` line prints before the message for the aborted `j` request. Why that order?
Q3. What should the retry button call, and why?
Practice only: not graded, not saved, not evidence.

10. Apply it: stretch tasks

  1. A real public API. Point the client at the Open Library search API: request https://openlibrary.org/search.json?q=<query>&limit=5&fields=title,author_name, and map its docs array (each item has title and author_name) to your display shape. Keep the debounce at 300 ms — a real API deserves the courtesy — and expect latency and orderings you do not control. Why does the abort/guard pair matter more now, not less?
  2. The DOM version. Replace setState with DOM updates: an input element wired to onKey(e.target.value), a results ul, a status line for loading/empty/error, and a retry button (a real button, not a clickable div) that calls runSearch(input.value). Every state change must be visible without colour alone.
  3. Bounded retries. Make the error state retry automatically up to twice, with 500 ms between attempts, and give up into the manual-retry state afterwards. What happens to a request that was aborted — should the automatic retry touch it?

11. Review prompt

Without looking back: walk the final transcript and name which state each line belongs to. Why does the abort message print after the second loading line? What did step 5 prove about debounce alone, and what did step 4 prove about abort alone? Which two error names can the catch see, and what does each mean? And why does retry call runSearch instead of fetching directly?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check