Checkpoint: Browser APIs

Published by Brayan K

This checkpoint consolidates the async and browser-API skills you have built — promise combinators, async iterators, cancellation, workers, observers, storage, and canvas — into one recap, a real build challenge, and a quick quiz.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Define the result and failure policy before choosing browser APIs

Build a report that consumes a finite stream of samples, computes a total, tries to save a cache snapshot and draws the values. The report should remain useful if caching fails. A newer refresh must replace older work, and disposal must prevent late writes to removed UI. Those are the integration contracts this checkpoint asks you to prove.

// Both operations start, and both outcomes remain visible.
const [analysis, cache] = await Promise.allSettled([
  Promise.resolve(12),
  Promise.reject(new Error("storage unavailable"))
]);
// Rendering may proceed because the essential analysis succeeded.
console.log(analysis.status, analysis.value);
console.log(cache.status, cache.reason.message);

// ✅ Expected output:
// fulfilled 12
// rejected storage unavailable

This is a policy choice, not a universal rule to ignore storage errors. A draft editor whose only durable copy is local storage needs a different failure policy. Promise Combinators (all, race, allSettled, any) owns aggregate outcomes; IndexedDB (Client-Side Database) owns real storage queries and transactions.

Bound a stream before materializing a report

async function* source() { yield 2; yield 4; yield 6; }
const values = [];
for await (const value of source()) {
  if (!Number.isInteger(value) || value < 0 || value > 100) throw new TypeError("invalid sample");
  if (values.length === 50) throw new RangeError("too many samples");
  values.push(value);
}
console.log(JSON.stringify(values));
console.log(values.reduce((total, value) => total + value, 0));

// ✅ Expected output:
// [2,4,6]
// 12

Streaming does not automatically imply bounded memory: collecting every item from an unlimited source still grows without bound. This report deliberately accepts at most fifty small integer samples. Async Iterators & for-await-of owns demand and cleanup. A production loader must cooperate with cancellation while awaiting its next result.

Use generation identity as well as cooperative cancellation

let generation = 0;
const first = ++generation;
const second = ++generation;
const events = [];
function commit(token, value) {
  if (token !== generation) return false;
  events.push(value);
  return true;
}
console.log(commit(second, "new"), commit(first, "old"));
console.log(events.join(", "));

// ✅ Expected output:
// true false
// new

Abort asks cooperating work to stop; generation identity prevents obsolete work from committing a visible result. Neither mechanism undoes an already-completed remote side effect. AbortController & Cancelling Async Work owns signal state; Web Workers (Background Threads) owns worker termination and message identity. A worker adapter must translate the report’s cancellation lifetime into its own protocol.

Choose observation only when there is something external to observe

This component owns its data and explicitly redraws after a successful refresh, so it does not need a MutationObserver to rediscover changes it made itself. MutationObserver (Watching the DOM) is appropriate when another component controls the DOM you must react to.

A large report below the fold might defer expensive rendering with IntersectionObserver (Lazy Load & Infinite Scroll). A tiny, explicitly requested chart does not need that extra lifecycle. Correct integration includes choosing when an API would add work without solving the current requirement.

The canvas represents selected data and has an accessible text equivalent. The Canvas API owns buffer resolution, drawing state and coordinate mapping. The compact chart here uses a fixed buffer so the exercise can focus on asynchronous ownership.

Make dependency boundaries reviewable

const input = [2, 4, 6];
const snapshot = Object.freeze({ schema: 1, values: Object.freeze(input.slice()) });
input[0] = 99;
console.log(JSON.stringify(snapshot));
console.log(Object.isFrozen(snapshot), Object.isFrozen(snapshot.values));

// ✅ Expected output:
// {"schema":1,"values":[2,4,6]}
// true true

The complete UI below accepts load, compute and save services. The demonstration uses an async generator, a deterministic computation and an in-memory recording cache. Those stand-ins expose the component’s state transitions; they do not prove a hosted API, real worker adapter or IndexedDB integration. The owning lessons contain real worker and database examples.

The cache service receives a versioned selected snapshot and is responsible for its actual transaction and migration policy. The compute service receives its own array copy and signal. A fulfilled cache promise means only that the service met its declared contract; it does not establish permanent retention or cross-device backup.

Guided exercise: keep optional failure separate

Fill the literal hints to inspect both outcomes and select the essential result. Do not turn a failed cache write into an invented successful write.

const [analysis, cache] = await Promise.___([Promise.resolve(8), Promise.reject("quota")]); // 👉 replace ___ with allSettled
if (analysis.status === "___") console.log(analysis.value); // 👉 replace ___ with fulfilled
console.log(cache.___); // 👉 replace ___ with status

// ✅ Expected output:
// 8
// rejected

Build brief: one refresh owns one visible report

Implement mountReport(root, services) for an empty HTMLElement and callable load, compute and save dependencies. Create a refresh button, live status and a 300 by 120 canvas. Snapshot the service function references when mounting. Do not invoke services until run() or the button requests a refresh.

Every run creates a fresh AbortController and supersedes the previous generation. Consume load(signal) as an async iterable, validating 1–50 integer samples in 0–100. Check cancellation after each yielded value and after stream completion. Then start compute(copy, signal) and save(frozenSnapshot, signal) together and collect both outcomes. Catch synchronous dependency throws as well as promise rejections.

Only the current, active generation may draw or change its final status. Require a successful safe-integer analysis total from 0 through 5000. A failed cache still permits a report marked cache unavailable. An essential failure shows Could not load report. The service contract owns the correctness of the total; the UI validates its representation.

run resolves to ready, failed, stale or disposed. dispose is terminal and idempotent: abort active work, detach the click listener and remove owned nodes. A non-cooperating dependency can remain pending, but its late result must not change the disposed UI. Failed refreshes leave the previous chart visible alongside the failure status; decide differently if your product must hide old data.

function mountReport(root, services) {
  if (!(root instanceof HTMLElement) || root.childNodes.length ||
      !services || !["load", "compute", "save"].every(key => typeof services[key] === "function")) {
    throw new TypeError("empty root and report services required");
  }
  const load = services.load, compute = services.compute, save = services.save;
  const button = document.createElement("button");
  button.type = "button"; button.textContent = "Refresh report";
  const status = document.createElement("p"); status.setAttribute("role", "status"); status.textContent = "Ready to load";
  const canvas = document.createElement("canvas");
  canvas.width = 300; canvas.height = 120;
  canvas.style.cssText = "width:300px;max-width:100%;height:auto";
  canvas.setAttribute("role", "img"); canvas.setAttribute("aria-label", "No report loaded");
  const context = canvas.getContext("2d");
  if (!context) throw new Error("2D context unavailable");
  root.append(button, status, canvas);
  let disposed = false, generation = 0, controller = null;
  function paint(values) {
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.fillStyle = "#ffffff"; context.fillRect(0, 0, 300, 120);
    const slot = 280 / values.length;
    context.fillStyle = "#2463eb";
    values.forEach((value, i) => context.fillRect(10 + i * slot, 110 - value, Math.max(1, slot - 2), value));
    const text = "Report values: " + values.join(", ");
    canvas.setAttribute("aria-label", text); canvas.textContent = text;
  }
  async function run() {
    if (disposed) return "disposed";
    const token = ++generation;
    controller?.abort(new Error("superseded"));
    const current = new AbortController(); controller = current;
    status.textContent = "Loading";
    try {
      const values = [];
      for await (const value of load(current.signal)) {
        current.signal.throwIfAborted();
        if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 100) {
          throw new TypeError("invalid sample");
        }
        if (values.length === 50) throw new RangeError("too many samples");
        values.push(value);
      }
      current.signal.throwIfAborted();
      if (!values.length) throw new RangeError("no samples");
      const snapshot = Object.freeze({ schema: 1, values: Object.freeze(values.slice()) });
      const [analysis, storage] = await Promise.allSettled([
        Promise.resolve().then(() => compute(values.slice(), current.signal)),
        Promise.resolve().then(() => save(snapshot, current.signal))
      ]);
      if (disposed || token !== generation) return "stale";
      current.signal.throwIfAborted();
      if (analysis.status !== "fulfilled") throw analysis.reason;
      const total = analysis.value;
      if (!Number.isSafeInteger(total) || total < 0 || total > 5000) throw new TypeError("invalid analysis");
      paint(values);
      status.textContent = "Total: " + total + (storage.status === "fulfilled" ? "; cached" : "; cache unavailable");
      return "ready";
    } catch {
      if (disposed || token !== generation) return "stale";
      status.textContent = "Could not load report";
      return "failed";
    }
  }
  function onClick() { void run(); }
  button.addEventListener("click", onClick);
  return Object.freeze({
    run,
    dispose() {
      if (disposed) return;
      disposed = true; generation++;
      controller?.abort(new Error("disposed"));
      button.removeEventListener("click", onClick);
      button.remove(); status.remove(); canvas.remove();
    }
  });
}
const root = document.createElement("section");
document.getElementById("app").append(root);
const saved = [];
const services = {
  async *load(signal) {
    signal.throwIfAborted();
    yield 20; yield 40; yield 60;
  },
  async compute(values, signal) {
    signal.throwIfAborted();
    return values.reduce((sum, value) => sum + value, 0);
  },
  async save(snapshot) { saved.push(snapshot); throw new Error("recording cache refused"); }
};
const ui = mountReport(root, services);
console.log(await ui.run());
console.log(root.querySelector('[role="status"]').textContent);
console.log(root.querySelector("canvas").getAttribute("aria-label"));
console.log(saved.length, Object.isFrozen(saved[0].values));
ui.dispose();
console.log(root.childNodes.length, await ui.run());
root.remove();

// ✅ Expected output:
// ready
// Total: 120; cache unavailable
// Report values: 20, 40, 60
// 1 true
// 0 disposed

Test an empty stream, an invalid late sample, fifty-one samples, a synchronous dependency throw, cache-only failure, an obsolete completion and disposal during a pending operation. Also test the actual adapters in their own environments before calling a product ready to ship. This checkpoint’s controlled demonstration is not a live-service integration test.

Practice quiz

What does this complete program print? const rows=await Promise.allSettled([Promise.resolve(4),Promise.reject("cache")]);console.log(rows.map(x=>x.status).join(","));

  • fulfilled,rejected
  • fulfilled,fulfilled
  • rejected,fulfilled
  • rejected,rejected

Answer: fulfilled,rejected. The two outcomes remain distinct so the caller can apply its policy.

Why use a generation check even after aborting old work?

  • It makes every server roll back
  • A dependency may ignore cancellation and finish late
  • It converts failures into successes
  • It removes the need to validate input

Answer: A dependency may ignore cancellation and finish late. Generation identity protects the visible commit even when a producer is not cooperative.

What does this complete program print? let n=0;async function* values(){yield 2;yield 3;}for await(const x of values())n+=x;console.log(n);

  • 2
  • 3
  • 5
  • 23

Answer: 5. The finite stream is consumed in order and summed.

When is a MutationObserver unnecessary for this small component?

  • Whenever the browser supports workers
  • Whenever storage is disabled
  • Whenever there is a canvas
  • When it already owns the data and explicitly updates its UI

Answer: When it already owns the data and explicitly updates its UI. Observing its own predictable changes would add an unnecessary feedback path.

What does this complete program print? const values=[1,2];const snapshot=Object.freeze({values:Object.freeze(values.slice())});values[0]=9;console.log(snapshot.values.join(","));

  • 1,2
  • 9,2
  • 1,9
  • TypeError

Answer: 1,2. The selected array copy is detached from later input-array mutation.

What does the recording cache in the demo establish?

  • A real IndexedDB transaction committed
  • The UI’s behavior at an injected cache boundary
  • Permanent backup
  • Cross-device synchronization

Answer: The UI’s behavior at an injected cache boundary. A labelled stand-in checks orchestration, while real storage requires its own integration checks.

What does this complete program print? const c=new AbortController();c.abort("old");const fresh=new AbortController();console.log(c.signal.aborted,fresh.signal.aborted);

  • false false
  • true true
  • true false
  • false true

Answer: true false. A new operation gets a fresh signal rather than resetting an aborted one.

Which result is allowed to update the final report?

  • Any result that eventually succeeds
  • Only the first request ever started
  • Every cached result regardless of generation
  • The current generation while the component remains active

Answer: The current generation while the component remains active. The component owns a precise lifetime and rejects stale visual commits.

Continue this course

Related lessons