Lawfare Academy

CS 220 — Web Applications, SQL and Software Engineering · Weeks 3–5

JavaScript state, asynchronous requests and rendering

Full teaching sequence and cumulative subject work

Study the complete on-site source sections below, then work the original example, changed-condition problem and transfer laboratory. Study MDN JavaScript fundamentals, DOM scripting and Fetch; CS50 Web JavaScript and User Interfaces. Trace loading, success, empty and error states.

Exercise a real HTTP route and its database boundary — primary material, constructed-response tasks, complete worked model and changed-case examination →

Asynchronous rendering and stale responses

A user can initiate request B while request A is still in flight. Network completion order need not match initiation order. Rendering whichever response arrives last can display stale state. Track the current request generation, and make success, error and loading transitions conditional on that generation. Cancellation can save work, but checking relevance is still useful because completion and cancellation can race.

Treat returned strings as data. textContent displays characters; inserting untrusted HTML can change document structure and introduce executable content in unsafe contexts. A valid JSON shape does not prove that an answer belongs to the currently selected customer.

Worked problem

The user selects customer A, then B. B returns first with five orders; A returns later with two. Trace the correct UI state, including the old request’s error handler.

Trace the complete reasoning
  1. Assign generation 1 to A and generation 2 to B. The current generation is 2.

  2. B can render five orders and clear its loading state because its generation is current.

  3. A’s success must not replace B’s list. Likewise, A’s later failure must not overwrite B’s success with an error.

  4. Verify the response object and render order descriptions as text. Keep selection identity, request identity and displayed data aligned.

Independent transfer problem

B returns an empty list while A is still running. What should appear, and why should an empty array not be treated as a fetch failure?

Compare the transfer solution

Render a successful empty state for B, not A’s previous data and not a network error. An empty collection is a legitimate result under the API contract. Ignore A when it completes. Test empty, malformed, denied and failed responses separately so their distinct meanings remain visible.

Learning objectives

  • Explain and trace the mechanisms in javascript state, asynchronous requests and rendering.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Study the mechanism

An interface is a state machine, even when written without a state-machine library. A request can be idle, loading, successful or failed; successful data can also be empty. Displaying unrelated content while a destination loads creates confusion because the user cannot distinguish navigation from an error. Render a destination-specific loading state and replace it with the requested content.

Promises represent work whose result is not yet available. await pauses the current asynchronous function, not the entire browser. A fetch promise can resolve for an HTTP error response, so inspect response.ok before interpreting the body as success. Handle malformed data separately from a failed connection. When two requests overlap, an earlier slower response can overwrite newer results. Use cancellation or a request identity check so the latest user intent wins.

When rendering untrusted text, use textContent or an escaping mechanism. Inserting external strings as HTML can turn data into executable markup. Keep state changes separate from visual effects where possible, making them easier to test. Define what happens when the user navigates away, presses twice or loses the connection. A spinner without a recoverable error state can leave the page indefinitely unusable.

Worked example

let requestNumber = 0;
async function loadOrders(output) {
  const current = ++requestNumber;
  output.textContent = "Loading work orders…";
  try {
    const response = await fetch("/api/orders");
    if (!response.ok) throw new Error("Request failed");
    const data = await response.json();
    if (!Array.isArray(data.orders)) throw new Error("Invalid response");
    if (current !== requestNumber) return;
    output.textContent = data.orders.length + " work orders";
  } catch (error) {
    if (current === requestNumber) output.textContent = "Could not load. Please retry.";
  }
}

The incrementing identifier makes an older response ineligible to replace a newer request. HTTP errors and malformed arrays reach the error state. textContent avoids treating returned strings as markup. The example does not render individual orders or implement the API; it demonstrates the request-state boundary. A real retry button can call the function again.

Check your understanding

Why check response.ok after fetch resolves?

  1. HTTP errors can still produce a resolved fetch response
  2. Resolution guarantees a 200 status
  3. JSON parsing verifies authorization
Answer and reasoning for every option

Correct: HTTP errors can still produce a resolved fetch response Transport completion and application success are different conditions.

Reconsider: Resolution guarantees a 200 status A server can respond with an error status successfully over the network.

Reconsider: JSON parsing verifies authorization Parsing a body does not establish access rights.

Transfer laboratory: Stale errors after newer success

Request A begins, then request B begins. B succeeds and A later fails. Explain why a generic catch block can erase the right screen.

Work through the full solution

If the catch unconditionally replaces the page, the obsolete A failure overwrites B’s current success. Apply the same request-identity or cancellation policy in success and error handlers. The authority to update the interface belongs to the most recent relevant request, not the last callback to run. Test both stale success and stale failure.

Evidence of understanding

Retain B and guard both completion paths, including errors.

Complete on-site teaching readings

These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.

  1. Control flow and error handling · Mozilla Contributors
  2. Functions · Mozilla Contributors
  3. Indexed collections · Mozilla Contributors
  4. Working with objects · Mozilla Contributors
  5. Using promises · Mozilla Contributors
  6. Using the Fetch API · Mozilla Contributors
  7. DOM scripting introduction · Mozilla Contributors

Open in My Learning to record progress →