Skip to lesson content
Web Technologies › Level 18
LEVEL 18 · ASYNC

Asynchronous JavaScript and APIs

Handle waiting, failures and competing responses with clear, owned outcomes.

📦 Promises📨 Fetch + JSON🧭 Request ownership🧪 Lab + MCQs
01

Learning Objectives

Async flow

Explain when code waits and when other work can proceed.

Responses

Check HTTP status before interpreting a body.

Data contract

Separate valid JSON from acceptable workshop records.

Ownership

Let only the newest request update the current result.

02

Asynchronous Work and the Event Loop

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
// In this simple example: A, D, C, B
03

Callbacks — A Starting Point

setTimeout(() => {
  console.log("Timer callback ran");
}, 500);

const doubled = [1, 2].map(value => value * 2);
// map finishes synchronously here: [2, 4]
04

Promises — Pending, Fulfilled or Rejected

function wait(milliseconds) {
  return new Promise(resolve => {
    setTimeout(resolve, milliseconds);
  });
}
wait(500).then(() => console.log("Wait completed"));
05

then, catch and Returning the Next Step

fetch("/api/workshops")
  .then(response => {
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error.message));
06

async and await — Read the Sequence Clearly

async function loadCatalog() {
  const response = await fetch("/api/workshops");
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  const data = await response.json();
  return data;
}
07

try, catch and finally — Outcome and Cleanup

setLoading(true);
try {
  const data = await loadCatalog();
  showCatalog(data);
} catch (error) {
  showError(error.message);
} finally {
  setLoading(false);
}
08

HTTP and an API Response Contract

Separate response decisions
Transport

Did the client receive a response or encounter a failure?

HTTP status

Does the status meet the operation’s contract?

Body format

Can the promised representation be parsed?

Record contract

Are the parsed fields and values acceptable?

09

Fetch — Check the Response Before Parsing

const response = await fetch("/api/workshops", {
  headers: { Accept: "application/json" }
});
if (!response.ok) {
  throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
10

JSON Parsing Is Not Schema Validation

if (!Array.isArray(data)) {
  throw new Error("Expected a workshop array");
}
for (const workshop of data) {
  if (!Number.isInteger(workshop.capacity) ||
      !Number.isInteger(workshop.reserved) ||
      workshop.reserved > workshop.capacity) {
    throw new Error("Invalid workshop record");
  }
}
11

UI States — Loading Is Part of the Task

Loading

A pending response is owned by the newest request.

Success / empty

Accepted records or a clear zero-record outcome.

Error

HTTP, transport, parsing or schema failure.

Canceled

The active request was intentionally aborted.

12

AbortController and Timeouts

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
try {
  const response = await fetch("/api/workshops", {
    signal: controller.signal
  });
  // Check status, parse and validate here.
} finally {
  clearTimeout(timer);
}
13

Overlapping Requests — Newest Result Owns the UI

const requestId = ++latestRequestId;
try {
  const data = await loadCatalog();
  if (requestId !== latestRequestId) return;
  showCatalog(data);
} finally {
  if (requestId === latestRequestId) setLoading(false);
}
14

Sequential Work, Promise.all and allSettled

const catalogPromise = loadCatalog();
const noticePromise = loadNotices();
const [catalog, notices] = await Promise.all([
  catalogPromise, noticePromise
]);
15

CORS, Credentials and Safe Rendering

const title = document.createElement("h4");
title.textContent = acceptedWorkshop.title;
card.append(title);
16

Premium Visualizer — Async Response Journey

Follow one fixed successful response through loading, status, parsing, validation and rendering. Use the approved timeline and playback controls. The live lab separately exercises success and failure paths with local simulated responses.

ASYNC API RESPONSE TRACE
Step 1 of 5
STEP 01

Start and own a catalog request

Assign a request ID and show loading while the promise is pending.

requestId = ++latestRequestId

What is happening?

Only this request may write the current result while it remains the latest owner.

17

Premium Interactive — Async Catalog Loader

Idle. Choose a simulated response and load it.

Accepted catalog cards

    Accepted payload

    No accepted payload yet.

    Request log

    []
    18

    Debugging — Locate the Failed Stage

    Pending

    Check whether the awaited operation ever settles and whether cancellation is wired.

    Response

    Separate a rejected request from a received error status.

    Data

    Inspect body parsing and the accepted record contract.

    Ownership

    Check every UI write, including catch and finally.

    19

    Interview Questions — Flip to Explain

    QUESTION

    Does async automatically move heavy code off the main thread?

    Click or press Enter to explain
    ANSWER

    No. An async function can still perform blocking synchronous work. Await suspends that function while an awaited promise is pending.

    QUESTION

    What does an async function return?

    Click or press Enter to explain
    ANSWER

    A promise. A returned value fulfills it; an uncaught error rejects it.

    QUESTION

    Does fetch reject just because HTTP status is 404?

    Click or press Enter to explain
    ANSWER

    Normally no. It can fulfill with a Response whose ok value is false. Inspect the status explicitly.

    QUESTION

    Why await response.json separately?

    Click or press Enter to explain
    ANSWER

    Reading and parsing the response body is asynchronous and can fail independently of receiving the response.

    QUESTION

    Does valid JSON prove the catalog record shape is valid?

    Click or press Enter to explain
    ANSWER

    No. Validate types, bounds, unique IDs and relationships according to the application contract.

    QUESTION

    Why guard finally with the request ID?

    Click or press Enter to explain
    ANSWER

    An older request must not clear a newer request’s loading state or change its current UI outcome.

    QUESTION

    Does Promise.all cancel other inputs when one rejects?

    Click or press Enter to explain
    ANSWER

    No. Rejection of the group does not automatically cancel already-started operations.

    QUESTION

    What should an empty successful response show?

    Click or press Enter to explain
    ANSWER

    A clear zero-record result and a finished loading state, rather than an error or perpetual spinner.

    20

    MCQ Practice — Predict the Async Outcome

    PRACTICE

    1. What does an async function return?

    PRACTICE

    2. Which order fits the simple A/timer B/promise C/D example?

    PRACTICE

    3. What should a promise chain return when the next step reads JSON?

    PRACTICE

    4. How does fetch normally handle a received HTTP 404?

    PRACTICE

    5. What does response.ok represent?

    PRACTICE

    6. What can response.json() do after a successful HTTP status?

    PRACTICE

    7. What is required after successfully parsing a catalog body?

    PRACTICE

    8. Which API supplies a signal for cancellation?

    PRACTICE

    9. Why can an older finally block cause a UI bug?

    PRACTICE

    10. In what order does Promise.all supply fulfilled group results?

    PRACTICE

    11. What happens to other started operations when Promise.all rejects?

    PRACTICE

    12. What should the latest successful empty catalog show?

    21

    Extra Practice — Reproduce Specific Async Outcomes

    Success

    Load success. Expected: four accepted records with remaining counts 18, 0, 30 and 12; total 60.

    Empty

    Load empty. Expected: no cards, accepted [] and a completed empty status.

    HTTP error

    Load HTTP 404. Expected: status-stage failure; no accepted payload.

    Parse failure

    Load malformed JSON. Expected: parsing failure after the successful response status.

    Contract failure

    Load invalid record shape. Expected: validation rejection before cards are rendered.

    Cancel

    Cancel during the scheduled delay. Expected: canceled state, busy false and no accepted cards.

    Slow old result

    Start slow success then fast empty. Expected: newest empty persists; old success is logged as ignored.

    Old cleanup

    • Start fast success then slow empty.
    • Expected: loading stays true for the newer request after the old completion; finally the newest empty appears.
    22

    Quick Revision

    Async: Waiting can yield control; heavy synchronous work still blocks.
    Promise: Track eventual fulfillment or rejection.
    Chain: Return the next promise to connect its outcome.
    Await: Suspend the async function, not the whole browser.
    Fetch: Check status before reading the body.
    Contract: Parsing and validation are separate stages.
    UI: Idle, loading, success, empty, error and canceled are explicit.
    Abort: Handle cancellation and release timers/listeners.
    Ownership: Guard success, failure and cleanup writes.
    Groups: Choose sequential or grouped work deliberately.
    23

    Glossary — Flip to Learn

    TERM

    Promise

    Click to see meaning
    DEFINITION

    Promise

    A representation of an eventual fulfillment value or rejection reason.

    TERM

    Pending

    Click to see meaning
    DEFINITION

    Pending

    The promise has not yet settled into fulfillment or rejection.

    TERM

    Fulfillment

    Click to see meaning
    DEFINITION

    Fulfillment

    Successful settlement with a value.

    TERM

    Rejection

    Click to see meaning
    DEFINITION

    Rejection

    Unsuccessful settlement with a reason.

    TERM

    Await

    Click to see meaning
    DEFINITION

    Await

    An operation that suspends an async function until the awaited outcome is available.

    TERM

    Response

    Click to see meaning
    DEFINITION

    Response

    The Fetch API representation of a received response and its body access.

    TERM

    JSON

    Click to see meaning
    DEFINITION

    JSON

    A text data representation that can be parsed into JavaScript values.

    TERM

    Schema validation

    Click to see meaning
    DEFINITION

    Schema validation

    Checking a parsed value against an expected data contract.

    TERM

    Abort signal

    Click to see meaning
    DEFINITION

    Abort signal

    A signal that compatible work observes to support cancellation.

    TERM

    Request ownership

    Click to see meaning
    DEFINITION

    Request ownership

    A rule deciding which asynchronous operation may update the current UI.

    24

    Final Challenge — A Loader with Owned Outcomes

    25

    Level 18 Complete?

    Before marking complete, explain an awaited response, handle one failure at each relevant stage and demonstrate cancellation plus both overlapping-request cases. Completion is a local study marker rather than an assessment score.