Book 1 · Lesson 1.3

Promises and async/await

  • Rewrite callback code with Promises and async/await
  • Identify where microtasks are scheduled
  • Read async Rust/Tokio handlers as a contrast (preview)

Prerequisites: 1.2

Promises represent a future value. async/await is syntax sugar over Promises — still microtasks under the hood.

Callback style (legacy)

fetch('/api/metrics/summary')
  .then((r) => r.json())
  .then((data) => updateCards(data))
  .catch((err) => showError(err));

async/await (modern)

async function loadMetrics() {
  try {
    const r = await fetch('/api/metrics/summary');
    const data = await r.json();
    updateCards(data);
  } catch (err) {
    showError(err);
  }
}

Each await yields the function — remainder schedules as microtasks when the Promise settles.

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');

Run synchronous code. console.log('A') executes immediately on the call stack.

Call stack

  • log('A')

Microtask queue

  • empty

Macrotask queue

  • empty

Console output

  • A

Contrast with Rust (preview)

JavaScript (browser)Rust + Tokio (ingestion/analyzer)
Concurrency modelSingle thread + event loopThread pool + async tasks
Async syntaxasync/await → microtasksasync/await → state machines
BlockingBlocks the whole tab.await yields task, not thread

Book 1.11 goes deeper on Tokio. For now: radar = JS loop, pipeline = Rust async.

Teach-back prompt

Does await fetch(...) block other tabs? Other SSE events in the same tab?

Callbacks → async/await

Lesson 1.3 check

1. async/await in JS schedules continuations as…