HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 4“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
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:
Explain the event loop well enough to predict ordering between synchronous code, promises, and timers.
Use async/await with explicit error paths instead of an unhandled rejection.
Cancel a request with AbortController and a timeout via AbortSignal.timeout.
Distinguish Promise.all from Promise.allSettled when loading the lesson and the tutor together.
Ignore stale responses when the learner navigates before a request finishes.
Retry idempotent GETs with a small cap, and refuse automatic retries of completion POSTs without an idempotency key.
Parse response bodies as unknown before they become domain types.
Keep the lesson UI usable when the tutor call aborts or returns a non-OK status.
Name the cost of abandoned in-flight model calls and of retry storms.
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:
Synchronous code runs until it awaits or returns.
Promise reactions (the code after await, or a .then) run as microtasks before the next timer.
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.
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
API
Role in this lesson
fetch
HTTP from the browser or Node.js 20+
AbortController / AbortSignal.timeout
Cancel stale calls and bound waits
Headers
Set Idempotency-Key and Accept
Response.json()
Read a body, then parse as unknown
URL
Build 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.
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.
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.
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
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.
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 error
UI behavior
Retry
timeout on tutor
Show the lesson, hide the draft, offer one manual retry
Manual only
aborted
Do not paint; the learner moved on
No
http 401 or 403
Send the learner to sign in
No
http 409 on complete
Refetch progress; the key may already have a fact
No blind POST
bad_json
Show a generic failure; log the status, not the body if it might contain another user's text
No
network on GET
One automatic retry, then a visible failure
Once
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";
functionjsonResponse(body:unknown, status =200): Response {
returnnewResponse(JSON.stringify(body),{
status,
headers:{"content-type":"application/json"},
});
}
test("discards a tutor draft when the visible lesson changed",async()=>{
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.
Implement requestJson, explainLesson, loadLesson, and completeLesson.
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.
Write the loadPlayer helper using Promise.allSettled and state which half the UI may ignore.
Document timeout values and which errors retry.
Describe how the React page will abort the signal on unmount. You do not need to build the component yet.
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
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.
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.
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.
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.
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.
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.
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.