AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 4

    Modern JavaScript, Async Programming and Web APIs

    TechLearningPro's tutor button looked fine in a demo and failed on a slow afternoon.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 04 · Full-Stack Engineering Foundations

    Lesson Overview

    TechLearningPro's tutor button looked fine in a demo and failed on a slow afternoon. A learner opened lesson 3, clicked Explain, then jumped to lesson 4 and clicked Explain again. The first request returned last and painted lesson 3's draft under lesson 4's heading. A third click timed out in the UI while the Node.js process kept waiting on the provider, so the token meter kept moving after the learner had left. The progress POST beside it had a different bug: a double click created two completion attempts with no idempotency key, and a retry of a lost response made the client show an error even though the quiz fact had been stored.

    This lesson is the runtime behavior under those clicks. JavaScript runs each turn of the event loop to completion, then drains promises. async/await is syntax over promises, not a second thread. The browser and the server share the Fetch and AbortController web APIs that let you cancel a stale tutor call and bound a slow one. You will build a typed client that parses JSON with lesson 3's rules, aborts on timeout, ignores outdated responses, and retries only idempotent reads.

    No provider SDK and no API key are required. The sample server is a local fetch against a stub you control.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Explain the event loop well enough to predict ordering between synchronous code, promises, and timers.
    2. Use async/await with explicit error paths instead of an unhandled rejection.
    3. Cancel a request with AbortController and a timeout via AbortSignal.timeout.
    4. Distinguish Promise.all from Promise.allSettled when loading the lesson and the tutor together.
    5. Ignore stale responses when the learner navigates before a request finishes.
    6. Retry idempotent GETs with a small cap, and refuse automatic retries of completion POSTs without an idempotency key.
    7. Parse response bodies as unknown before they become domain types.
    8. Keep the lesson UI usable when the tutor call aborts or returns a non-OK status.
    9. Name the cost of abandoned in-flight model calls and of retry storms.
    10. Connect this client to React Fundamentals and Component Architecture and to /learn/nodejs fetch on the server.

    Prerequisites

    • Lessons 1–3: tutor drafts are not completion facts, secrets stay off the client, and JSON is parsed from unknown. See TypeScript for Production Full-Stack Development.
    • You can read async functions and import. The language primer for types is /learn/typescript.
    • Node.js 20 or newer, so fetch, AbortController, and AbortSignal.timeout exist in the runtime you pinned in lesson 2. Verify with node --version.
    • No cloud account. The tests call a stub fetch implementation in memory.

    Detailed Core Concepts

    One thread, many waits

    JavaScript on the main thread of a browser tab, and by default on a Node.js process, executes one function body at a time. When you await a fetch, the function pauses and the runtime is free to handle other events: a click, a timer, another request's response. The pause is not parallel CPU work. It is a scheduled continuation.

    Order that matters for the tutor bug:

    1. Synchronous code runs until it awaits or returns.
    2. Promise reactions (the code after await, or a .then) run as microtasks before the next timer.
    3. Timers and I/O callbacks run afterward.

    You do not need to memorize the HTML event loop specification to ship this feature. You do need to stop assuming that an earlier click's response will arrive earlier. The network does not offer that guarantee. The client must tag each request with the lesson id it was for and discard responses that no longer match the visible lesson.

    Promises and async functions

    A promise is a value that settles later as fulfilled or rejected. async functions return a promise. await either yields the fulfilled value or throws the rejection into the surrounding try. A rejection with no await, .catch, or try is an unhandled rejection. In a browser it becomes a console error and a possible process warning on Node.js. In this client, every request path catches failures and returns a typed result, the same shape as lesson 3's ParseResult.

    typescript
    type AsyncResult<T> =
    | { ok: true; value: T }
    | { ok: false; error: "timeout" | "aborted" | "http" | "bad_json" | "network" };

    Throwing across a React render or a request handler is reserved for defects. Expected failures are data.

    AbortController

    AbortController produces an AbortSignal. Pass the signal to fetch. Call controller.abort() when the learner leaves the lesson, or use AbortSignal.timeout(ms) when the clock expires. The fetch rejects with an AbortError (DOMException name AbortError, or a timeout error depending on the runtime). Treat both as "this result must not paint," and map timeout to the tutor fallback from lesson 1.

    Aborting the client fetch does not always abort work a remote provider already started. For your own API, propagate the signal to the outbound model call so the server stops waiting. For a provider that bills once generation starts, cancellation is a cost control you must verify in that provider's current docs when you bind a real port. This lesson's stub honors the signal so the client behavior is testable.

    all versus allSettled

    The lesson page needs the lesson body even when the tutor fails. Promise.all rejects if either call rejects, which would blank the page because a draft failed. Promise.allSettled waits for both and reports each outcome. Use all when every result is required, such as branding ids that must all parse. Use allSettled when the product can degrade, which is the tutor panel next to a required lesson payload.

    Idempotency and retries

    A GET of lesson content can be retried. Repeating it does not create a second fact. A POST that marks a quiz complete must not be retried blindly: the first request may have succeeded and the response was lost. Send an Idempotency-Key header the server stores with the fact, and retry only when the client knows the server treats that key as the same write. This lesson's client retries GET twice on network failure and does not auto-retry POST. The completion function requires the caller to pass a key and sends it once.

    Web APIs you will actually use

    APIRole in this lesson
    fetchHTTP from the browser or Node.js 20+
    AbortController / AbortSignal.timeoutCancel stale calls and bound waits
    HeadersSet Idempotency-Key and Accept
    Response.json()Read a body, then parse as unknown
    URLBuild the lesson URL without string concatenation bugs

    Streaming tutor text with ReadableStream and server-sent events is a later lesson. The client shape here returns one draft. Do not half-implement a stream parser you have not tested against disconnects.

    Deterministic control around a slow dependency

    The event loop, the abort signal, and the idempotency key are deterministic. The draft text may still be probabilistic. Cancellation means the probabilistic work does not get to update the screen after the learner has moved on, and it does not get to update completion at all.

    Architecture and Request Flow

    sequenceDiagram
      participant UI as Lesson player
      participant Client as ApiClient
      participant API as TechLearningPro API
      participant Model as Model port
    
      UI->>Client: explain(lesson 4, signal)
      Client->>API: POST /tutor AbortSignal
      Note over UI: Learner opens lesson 5
      UI->>Client: abort previous signal
      Client-->>API: abort
      API->>Model: abort in-flight call
      API-->>Client: aborted
      Client-->>UI: ignored stale result
      UI->>Client: GET /lessons/5
      Client->>API: GET with timeout
      API-->>Client: lesson JSON
      Client-->>UI: parsed lesson

    The progress POST is a separate arrow with an idempotency key and no dependence on the tutor response.

    Step-by-step Implementation

    Place the client in packages/web-client/src. It depends only on the domain parsers' ideas; the sample includes a minimal lesson parser so this package stays runnable without a monorepo wire-up. Use the real parseTutorDraft from lesson 3 when you join the packages.

    Step 1: Typed fetch with timeout and abort

    packages/web-client/src/http.ts

    typescript
    export type HttpError = "timeout" | "aborted" | "http" | "bad_json" | "network";
    export type HttpResult<T> =
    | { ok: true; status: number; value: T }
    | { ok: false; error: HttpError; status?: number };
    export interface RequestOptions {
    method: "GET" | "POST";
    url: string;
    body?: unknown;
    signal: AbortSignal;
    headers?: Record<string, string>;
    timeoutMs: number;
    }
    function combineSignals(user: AbortSignal, timeoutMs: number): AbortSignal {
    const timeout = AbortSignal.timeout(timeoutMs);
    return AbortSignal.any([user, timeout]);
    }
    export async function requestJson(options: RequestOptions): Promise<HttpResult<unknown>> {
    try {
    const response = await fetch(options.url, {
    method: options.method,
    signal: combineSignals(options.signal, options.timeoutMs),
    headers: {
    accept: "application/json",
    ...(options.body ? { "content-type": "application/json" } : {}),
    ...options.headers,
    },
    body: options.body ? JSON.stringify(options.body) : undefined,
    });
    if (!response.ok) return { ok: false, error: "http", status: response.status };
    let value: unknown;
    try {
    value = await response.json();
    } catch {
    return { ok: false, error: "bad_json", status: response.status };
    }
    return { ok: true, status: response.status, value };
    } catch (error) {
    if (isAbort(error)) {
    const reason = options.signal.aborted ? "aborted" : "timeout";
    return { ok: false, error: reason };
    }
    return { ok: false, error: "network" };
    }
    }
    function isAbort(error: unknown): boolean {
    return error instanceof DOMException && (error.name === "AbortError" || error.name === "TimeoutError");
    }

    AbortSignal.any is available in current Node.js 20+ and modern browsers. If npx tsc or Node on your pinned version rejects it, check the Node.js documentation for that version and use a small helper that aborts a parent controller when either signal aborts. Do not drop cancellation to silence the type error.

    response.json() is typed loosely by the DOM libs. The return type here is unknown on purpose, matching lesson 3.

    Step 2: Ignore stale tutor responses

    packages/web-client/src/tutor-client.ts

    typescript
    import { requestJson, type HttpResult } from "./http.js";
    export interface TutorDraftView {
    lessonId: string;
    text: string;
    promptVersion: string;
    }
    export interface ExplainInput {
    apiBase: string;
    lessonId: string;
    question: string;
    signal: AbortSignal;
    /** Latest lesson the UI is showing. Compared after the response arrives. */
    visibleLessonId: () => string;
    }
    function parseDraft(value: unknown, lessonId: string): TutorDraftView | undefined {
    if (typeof value !== "object" || value === null) return undefined;
    const body = value as Record<string, unknown>;
    if (body.lessonId !== lessonId) return undefined;
    if (typeof body.text !== "string" || body.text.trim().length === 0) return undefined;
    if (typeof body.promptVersion !== "string") return undefined;
    return { lessonId, text: body.text.trim(), promptVersion: body.promptVersion };
    }
    export async function explainLesson(input: ExplainInput): Promise<HttpResult<TutorDraftView>> {
    const result = await requestJson({
    method: "POST",
    url: `${input.apiBase}/tutor`,
    body: { lessonId: input.lessonId, question: input.question },
    signal: input.signal,
    timeoutMs: 8_000,
    });
    if (!result.ok) return result;
    if (input.visibleLessonId() !== input.lessonId) {
    return { ok: false, error: "aborted" };
    }
    const draft = parseDraft(result.value, input.lessonId);
    if (!draft) return { ok: false, error: "bad_json", status: result.status };
    return { ok: true, status: result.status, value: draft };
    }

    The check against visibleLessonId closes the race even if abort loses a race with an already-buffered response. Abort is still required so the server can stop work.

    Step 3: Idempotent GET retry, single POST

    packages/web-client/src/lesson-client.ts

    typescript
    import { requestJson, type HttpResult } from "./http.js";
    export interface LessonView {
    lessonId: string;
    title: string;
    }
    async function getOnce(url: string, signal: AbortSignal): Promise<HttpResult<unknown>> {
    return requestJson({ method: "GET", url, signal, timeoutMs: 4_000 });
    }
    export async function loadLesson(apiBase: string, lessonId: string, signal: AbortSignal): Promise<HttpResult<LessonView>> {
    const url = `${apiBase}/lessons/${encodeURIComponent(lessonId)}`;
    let result = await getOnce(url, signal);
    if (!result.ok && result.error === "network") {
    result = await getOnce(url, signal);
    }
    if (!result.ok) return result;
    const body = result.value;
    if (typeof body !== "object" || body === null) return { ok: false, error: "bad_json" };
    const record = body as Record<string, unknown>;
    if (record.lessonId !== lessonId || typeof record.title !== "string") {
    return { ok: false, error: "bad_json" };
    }
    return { ok: true, status: result.status, value: { lessonId, title: record.title } };
    }
    export async function completeLesson(input: {
    apiBase: string;
    lessonId: string;
    idempotencyKey: string;
    signal: AbortSignal;
    }): Promise<HttpResult<{ lessonId: string }>> {
    const result = await requestJson({
    method: "POST",
    url: `${input.apiBase}/lessons/${encodeURIComponent(input.lessonId)}/complete`,
    body: { lessonId: input.lessonId, source: "quiz_passed" },
    headers: { "idempotency-key": input.idempotencyKey },
    signal: input.signal,
    timeoutMs: 4_000,
    });
    if (!result.ok) return result;
    return { ok: true, status: result.status, value: { lessonId: input.lessonId } };
    }

    One network retry for GET. Zero automatic retries for POST. The server that receives idempotency-key must store the first outcome and return it for a duplicate key. That server behavior is a contract you will implement with the API lessons; the header is the client half.

    Step 4: Load lesson and tutor without coupling their fates

    typescript
    export async function loadPlayer(apiBase: string, lessonId: string, signal: AbortSignal) {
    const [lesson, tutor] = await Promise.allSettled([
    loadLesson(apiBase, lessonId, signal),
    explainLesson({
    apiBase,
    lessonId,
    question: "Summarize this section",
    signal,
    visibleLessonId: () => lessonId,
    }),
    ]);
    return { lesson, tutor };
    }

    If you render this in React, put it in an event handler or a data library, not in the render body. Starting a fetch during render duplicates requests under Strict Mode and recreates the stale-response bug. The component lesson shows the effect and cleanup that aborts on unmount. This lesson stops at the client functions.

    Step 5: Run tests

    bash
    node --experimental-strip-types --test src/http.test.ts

    No listening port is required. The test installs a stub on globalThis.fetch.

    Security

    • Authentication cookies or bearer tokens belong on calls to your API. This sample omits the header so the lab has no token to leak. When you add one, read it from an httpOnly cookie set by the server, or from a memory-only variable the server issued. Do not put a model provider key in this client. The client talks to your origin only.
    • Authorization is still the server's job. Hiding a button is not a control. The complete POST must fail on the server when the quiz has not passed, even if this client sends source: "quiz_passed".
    • Input validation happens again on the server. The client's parseDraft protects the UI from painting garbage; it does not protect the database.
    • Least privilege: the browser client can call lesson and tutor routes. It cannot call a provider host. Content Security Policy on the app should not need the provider origin.
    • Idempotency keys must be unguessable and unscoped across users. A key of lesson-01 would let one user replay another's completion semantics if the server keyed only on that string. Use a random id per attempt, and bind it server-side to the session's user and tenant.
    • Cancellation must not be treated as success. An aborted complete POST leaves the UI unknown until a GET of progress confirms the fact.

    Error Handling

    Client errorUI behaviorRetry
    timeout on tutorShow the lesson, hide the draft, offer one manual retryManual only
    abortedDo not paint; the learner moved onNo
    http 401 or 403Send the learner to sign inNo
    http 409 on completeRefetch progress; the key may already have a factNo blind POST
    bad_jsonShow a generic failure; log the status, not the body if it might contain another user's textNo
    network on GETOne automatic retry, then a visible failureOnce

    requestJson converts rejections into HttpResult, so callers do not grow a tree of try/catch with different string matching. Log error and status with the lesson id. Do not log the question text if it might contain personal notes; log its length.

    Testing

    packages/web-client/src/http.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { explainLesson } from "./tutor-client.js";
    import { loadLesson } from "./lesson-client.js";
    function jsonResponse(body: unknown, status = 200): Response {
    return new Response(JSON.stringify(body), {
    status,
    headers: { "content-type": "application/json" },
    });
    }
    test("discards a tutor draft when the visible lesson changed", async () => {
    globalThis.fetch = async () =>
    jsonResponse({
    lessonId: "lesson_03",
    text: "Old lesson explanation",
    promptVersion: "tutor-explain-v1",
    });
    const result = await explainLesson({
    apiBase: "https://learn.example",
    lessonId: "lesson_03",
    question: "Explain",
    signal: new AbortController().signal,
    visibleLessonId: () => "lesson_04",
    });
    assert.equal(result.ok, false);
    if (!result.ok) assert.equal(result.error, "aborted");
    });
    test("retries a lesson GET once on network failure", async () => {
    let calls = 0;
    globalThis.fetch = async () => {
    calls += 1;
    if (calls === 1) throw new TypeError("network down");
    return jsonResponse({ lessonId: "lesson_04", title: "Async" });
    };
    const result = await loadLesson("https://learn.example", "lesson_04", new AbortController().signal);
    assert.equal(result.ok, true);
    assert.equal(calls, 2);
    if (result.ok) assert.equal(result.value.title, "Async");
    });
    test("maps an aborted fetch to aborted", async () => {
    const controller = new AbortController();
    globalThis.fetch = async (_url, init) => {
    assert.ok(init?.signal);
    controller.abort();
    throw new DOMException("aborted", "AbortError");
    };
    const result = await explainLesson({
    apiBase: "https://learn.example",
    lessonId: "lesson_04",
    question: "Explain",
    signal: controller.signal,
    visibleLessonId: () => "lesson_04",
    });
    assert.deepEqual(result, { ok: false, error: "aborted" });
    });

    The tests replace globalThis.fetch. Restore it if you add tests in the same process that need the real fetch. Prefer this stub over a live server so the lab stays offline and free.

    Add a test that completeLesson sends idempotency-key and calls fetch once. Count calls. A second automatic call is a failure.

    Performance and Cost

    Tutor latency is capped at 8 seconds by timeoutMs. Lesson GET is capped at 4 seconds and may run twice, so the worst case before the UI gives up is about 8 seconds plus a little scheduling delay. Show the lesson shell immediately; do not await the tutor before painting the excerpt. Promise.allSettled encodes that policy.

    In-flight model calls are the cost risk. Every abandoned Explain that the server does not abort can still be billed. Propagate AbortSignal from the player to the API and from the API to the model port. Measure abort rate next to token spend. A high abort rate with high spend means the server is ignoring the signal.

    Retrying GET is cheap if the payload is a small JSON lesson. Retrying it in a loop on a 500 from your own bug is a self-inflicted outage. The single retry is only for network, not for http 500. Fix the server.

    N+1 fetches—one request per paragraph—belong in a later data-loading lesson. This client loads one lesson and one optional draft. Batch on the server if a page needs many sections, so the browser does not open dozens of connections.

    Cache lesson JSON that is public and versioned. Do not cache POST /tutor in a shared HTTP cache. The response is per question and per authorization decision.

    Knowledge Check

    1. What problem does this async client solve?

    It keeps TechLearningPro's lesson on screen when the tutor is slow, stops a stale draft from painting on the wrong lesson, and stops a lost response from turning into a duplicate completion write. It matches the event loop you actually have: responses arrive when they arrive, not in click order.

    2. What alternatives exist, and when would you choose each?

    Promise.allSettled fits a required lesson plus an optional draft. Promise.all fits a set of parses that are all required. Automatic retry fits idempotent GET on network errors. A POST retry fits only with an idempotency key the server honors. A streaming response fits long tutor output and is a later lesson, after cancellation and parsing are already solid. Web Workers fit heavy CPU, not a fetch.

    3. Which data, identity, and trust boundaries matter?

    The client calls only your API. The provider key stays on the server. JSON is unknown until parsed. The idempotency key is bound to the signed-in user on the server. Abort means "do not paint," not "the write failed" or "the write succeeded."

    4. What can fail, and how should the system respond?

    Timeouts and network errors become HttpResult codes. A changed visibleLessonId drops the draft. HTTP errors do not retry except the single GET network retry. Completion sends one POST with a key and then refetches progress if the outcome is unclear. Unhandled rejections should not occur on these paths because requestJson catches them.

    5. How would you test quality, security, performance, and cost?

    Stub fetch to return out of order, to throw a network error once, and to reject with AbortError. Assert call counts so POST is not retried. Security review checks the client has no provider key and that the idempotency key is random. Performance review checks timeouts and that the lesson paint does not wait on the tutor. Cost review checks that abort reaches the server before a live model is attached.

    Hands-on Assignment

    Lab note. Stub fetch. Do not call a model provider. Do not put keys in headers.

    Problem. Implement the client so a lesson 3 draft cannot render after the learner moved to lesson 4, and so a completion POST is not repeated automatically.

    Tasks.

    1. Implement requestJson, explainLesson, loadLesson, and completeLesson.
    2. Run the three tests in this lesson and add a fourth that counts fetch calls for completeLesson and expects one call with an idempotency-key header.
    3. Write the loadPlayer helper using Promise.allSettled and state which half the UI may ignore.
    4. Document timeout values and which errors retry.
    5. Describe how the React page will abort the signal on unmount. You do not need to build the component yet.
    6. Note what the server must do with AbortSignal before a real model port is safe to spend money on.

    Deliverable. Source, test output including the call count, the timeout table, and the abort note.

    Challenge. Two overlapping explainLesson calls share a generation counter instead of only an abort signal. Show that a buffered response from generation 1 is dropped when generation 2 has started, even if abort did not fire in time.

    Rubric. Conceptual accuracy 20%. Working client 25%. Security of keys and idempotency 20%. Tests for stale responses and retries 20%. Timeout and abort notes 15%.

    Common Mistakes

    1. Painting responses in arrival order. Symptom: lesson 4 shows lesson 3's tutor text. Cause: no abort and no visible-lesson check. Fix: both controls in explainLesson.
    2. Awaiting the tutor before showing the lesson. Symptom: a slow model blanks the player. Cause: Promise.all or a single combined request with no fallback. Fix: allSettled and paint the lesson first.
    3. Retrying POST on any error. Symptom: duplicate completions or duplicate token spend. Cause: a generic retry wrapper. Fix: retry GET network errors once; POST only with a server-honored idempotency key.
    4. Leaving the server call running after abort. Symptom: the UI stopped and the token bill did not. Cause: the signal never reached the model port. Fix: thread AbortSignal through the API.
    5. Reading response.json() as a typed object. Symptom: the string "true" returns, now inside a "typed" client. Cause: the compiler trusts the annotation and the runtime does not. Fix: type the body as unknown and parse.
    6. Starting fetch during render. Symptom: doubled requests and stale state under Strict Mode. Cause: side effects in render. Fix: event handlers or an effect with cleanup, covered in the React lesson.
    7. Treating timeout and success as the same empty state. Symptom: support cannot tell "learner left" from "provider down." Cause: one boolean failed. Fix: the HttpError union and metrics per code.

    Summary

    JavaScript concurrency here is an event loop plus promises. async/await keeps the code readable and still needs a typed result for timeout, abort, HTTP errors, and bad JSON. AbortController and a visible-lesson check stop stale tutor drafts. Promise.allSettled lets the lesson render when the draft does not. GET may retry once on network failure. Completion POSTs carry an idempotency key and are not looped. The client speaks only to your API, and every body is parsed before it is shown.

    Next Lesson Preview

    React Fundamentals and Component Architecture puts this client behind a lesson page that paints the excerpt immediately, fills the tutor panel only when a current draft arrives, and aborts on unmount. The server half of the same fetch lives on Node.js.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.