Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 39 ยท Practice and Review

Practice Exercises with Solutions

Twelve graded AJAX, JSON and fetch exercises with hints and runnable solutions: parsing, errors, POST, parallel requests, safe rendering, abort, timeouts, retries and pagination.

You learn to build AJAX features by building them. This lesson gives you twelve exercises that cover the whole track, from parsing a JSON string to cancelling stale requests and walking through paginated results. They are graded: the first four are warm-ups, the next four combine ideas, and the last four are the kind of problems that appear in real code reviews and interviews.

Each exercise states a task and gives a hint. Try it yourself first, ideally in a scratch file or in the editors below with the solution code cleared, and only then read the solution. The solutions run right here against fake servers (small functions that behave like fetch and answer instantly with real Response objects), so every result is reproducible and no real network is needed.

flowchart LR
  A["Warm-ups 1-4<br/>JSON, ok, URLs"] --> B["Combine 5-8<br/>POST, errors,<br/>parallel, DOM"]
  B --> C["Real-world 9-12<br/>abort, timeout,<br/>retry, pages"]

Three levels: single skills, combined skills, and production concerns.

Warm-ups: exercises 1 to 4

Exercise 1: parse without crashing. Write safeParse(text, fallback) that returns the parsed value, or fallback if the text is not valid JSON. What should safeParse('null', 'x') return, and why? See parse and stringify.

Hint: JSON.parse throws a SyntaxError; catch it. Is the text null valid JSON?

Exercise 2: serialize for sending. Turn a user object into pretty-printed JSON (two-space indentation) that omits the password field. The object also contains a Date. What does the date look like in the output? See revivers, replacers and toJSON.

Hint: the second argument of JSON.stringify can be a function.

Exercise 3: a getJson helper. Write getJson(url) that returns parsed JSON for a 2xx answer and otherwise throws an HttpError carrying the status and the body (parsed if possible, plain text if not). A server error may answer with plain text, not JSON. See handling errors in fetch.

Hint: fetch does not reject for 404. Read the body with text() once, then try JSON.parse.

Exercise 4: build a query string. Write buildSearchUrl(path, params) that skips values that are undefined, null or an empty string, but keeps 0 and false. Spaces and & must be encoded.

Hint: URLSearchParams does the encoding for you. Which values must you filter yourself?

Solutions 1 to 4

For exercise 1, 'null' is valid JSON, so the result is null, not the fallback: the fallback is for broken text only. In exercise 2 the replacer sees the date already converted by its toJSON method, so it appears as an ISO 8601 string in UTC.

JS Solutions 1 and 2: parse and stringify

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Solutions 3 and 4: getJson and buildSearchUrl

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The 404 and the 500 end up in the same catch as the offline case, which is the whole point of getJson; only the type of error differs, and that difference drives the user-facing message in exercise 6.

Combine skills: exercises 5 to 8

Exercise 5: send JSON. Write postJson(url, data) that sends the data as a JSON body with the right Content-Type. The fake server answers 201 with the saved record, 422 with field errors if name is missing, and 415 if the Content-Type is not JSON. Show all three outcomes. See sending data.

Hint: the headers object and JSON.stringify are both your job; fetch will not do either.

Exercise 6: friendly messages. Write explain(error) that turns any failure into a sentence for the user: network down, timeout, 404, 401/403, 429, 5xx, a 4xx with a message from the server, unreadable JSON. Never show raw technical text such as "Failed to fetch".

Hint: branch on error.name, instanceof and error.status, in that order of specificity.

Exercise 7: parallel requests with partial failure. A dashboard needs a profile, posts and comments. The comments service is down. Load all three in parallel, and show whatever succeeded plus a list of what failed. Prove that the calls ran in parallel. See async/await for requests.

Hint: Promise.all gives up at the first failure; its sibling allSettled waits for everything.

Exercise 8: render safely. Render a list of posts into the DOM with loading, empty and error states. One post title contains <img src=x onerror=...>; it must appear as text, not run. See rendering API data and AJAX security.

Hint: never assemble HTML from data. Create elements and set textContent.

Solutions 5 to 8

JS Solutions 5 and 6: postJson and explain

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 5 prints the 415 for the forgotten header so you can recognize it when you meet it in the Network panel. In exercise 6 the order of the checks matters: the cheapest rule would be "any TypeError is a network error", but a timeout is a DOMException, so it must be tested first by name.

JS Solution 7: parallel requests with allSettled

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Starting all three calls before awaiting is what makes them parallel; the array passed to allSettled is built from three calls that are already running. The timing check proves it: sequential awaits would take about 120 ms.

Solution 8: render a list safely

Press "Load posts": the third title shows up as visible text, tags and all, and no img element is created. Replace item.textContent = post.title with item.innerHTML = post.title and press the button again to see why this rule exists: the tag is now parsed as HTML, so a broken-image icon appears instead of the text, and its onerror handler runs (the sandbox may block the alert itself, but the handler still ran).

Real-world problems: exercises 9 to 12

Exercise 9: ignore stale results. A search box sends a request per keystroke. The request for ca is slow, the one for cat is fast, so the answers arrive out of order. Make sure only the latest query ever shows results. See cancelling requests.

Hint: abort the previous request before starting a new one, and treat AbortError as "ignore".

Exercise 10: a timeout that explains itself. Write fetchWithTimeout(url, { ms, signal }). It must fail with a clear "timed out" error when the server is too slow, but a user cancellation must stay an AbortError. Both can use the same signal mechanism, so how do you tell them apart?

Hint: check which of the two signals reports aborted.

Exercise 11: retry with backoff. Write retry(task, options) that retries a failing async task up to a limit, waiting twice as long each time (100 ms, 200 ms, ...). It must not retry errors that cannot succeed (a 404). Make the waiting replaceable so you can test it. See retries and backoff.

Hint: a shouldRetry(error) callback and an injectable sleep make this small and testable.

Exercise 12: follow the cursor. An API returns { items, nextCursor } and a missing nextCursor marks the last page. Write fetchAllPages(fetchPage) that returns every item. A broken server might never stop returning a cursor: protect your program. See live search and pagination.

Hint: a loop with a hard page limit is safer than while (true).

sequenceDiagram
  participant U as User
  participant S as Search code
  participant N as Network
  U->>S: types "ca"
  S->>N: request "ca" (slow)
  U->>S: types "cat"
  S->>N: abort "ca", send "cat" (fast)
  N-->>S: results for "cat"
  Note over S: the "ca" answer never reaches the screen

Aborting the previous request means a late, stale answer cannot overwrite a newer one.

Solutions 9 to 12

JS Solutions 9 and 10: abort and timeout

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first block shows the bug on purpose: both answers arrive and the slow, stale one is shown last. In the fix, aborting rejects the old promise with an AbortError, which the catch block treats as "ignore". For exercise 10 notice the test timeout.aborted && !(signal && signal.aborted): the combined signal is aborted in both cases, so only the individual signals can tell you the reason.

JS Solutions 11 and 12: retry and cursor pagination

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In exercise 11, sleep is replaced by a function that only records the requested delay, so the whole run is instant and the waits ([100, 200] for the first case, [100, 200, 400] for the last) can be checked exactly. Retrying four times in total (one try plus three retries) and then throwing the last error means the caller always learns what finally failed. Exercise 12 never trusts the server to stop: the page limit turns an infinite loop into an error you can read.

If you got stuck, that is useful information. Reread the lesson named next to the exercise, clear the editor and rebuild the solution from memory. Doing it twice is worth more than reading five solutions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does safeParse('null', 'fallback') return, and why?

    null is a legal JSON value, so JSON.parse returns null. The fallback is only used when parsing throws.
  2. 2. Why is Promise.allSettled a better fit than Promise.all for the dashboard in exercise 7?

    Promise.all rejects on the first failure. allSettled always resolves with a status for each promise, which suits partial dashboards.
  3. 3. In the timeout exercise, how do you tell a timeout from a user cancellation?

    The combined signal is aborted in both cases. The individual signals tell you which one fired.
  4. 4. Why does fetchAllPages use a for loop with maxPages instead of while (true)?

    Never trust a remote system to terminate your loop. A hard limit turns an endless loop into a clear error.

Summary

  • Parsing can throw, so wrap it; remember that null is valid JSON and a replacer function can drop fields such as passwords.
  • fetch resolves for HTTP errors: check response.ok, read the body once, and throw a typed error so callers can react by kind.
  • Sending JSON means setting Content-Type and calling JSON.stringify yourself; map errors to friendly messages in one function.
  • Start parallel requests before awaiting them, and use allSettled when partial results are useful.
  • Build DOM from data with textContent, never with markup strings.
  • Abort stale requests, tell timeouts from cancellations by checking each signal, retry only errors that can pass (with growing delays), and put a hard limit on loops driven by a server.

Next: AJAX, JSON and Fetch Interview Questions