TSTypeScript · First PrinciplesBuild judgment for vibe coding
0%
M02 1 hr 45 min CodePilot P0

Async and streams

Async Is a Protocol, Not Magic

Predict execution order, then build a mock review tool that streams, times out, and cancels.

By the end, you can:Explain synchronous work, microtasks, and timers;Represent incremental events with AsyncIterable;Carry AbortSignal through waiting operations
01
Start here

Who continues the work after await?

An async function runs immediately until its first await. Code after await continues as a microtask; a timer callback waits for a later task. These are scheduled turns, not parallel threads.

Draw the order before adding more await expressions.

TypeScript Lab

What is await waiting for?

Write down the A–E order, run it, then move await and explain the change.

正在加载 TypeScript 编辑器…
Diagnostics 0

运行后显示诊断。

Output

等待执行。

Need a hint?

Synchronous code runs first, Promise continuations are microtasks, and timers run later.

02
Failure path

An unawaited Promise does not send its error back automatically

If you forget await or return, an outer try/catch only covers the synchronous start. The later rejection may become unhandled.

Do not hide it with catch(() => undefined). Decide who owns the error.

TypeScript
async function start() {
  try {
    runReview(); // 没有 await,也没有 return
  } catch (error) {
    // 捕获不到 runReview 之后的 rejection
  }
}
03
Incremental results

A stream is a lifecycle, not just several callbacks

AsyncIterable lets a consumer pull values with for await...of and naturally represents completion, failure, and stopping early. Named events are clearer than raw strings.

  • Emit only one terminal event
  • Do not emit more text after cancellation
  • Release timers or connections in finally
04
Reliability

Cancellation must travel through the whole call chain

Pass AbortSignal into every operation that can wait. Timeouts and Ctrl+C may use different controllers but should become a clear domain reason.

finally is the last line of defense for cleanup.

05
CodePilot P0

Finish a cancellable mock streaming CLI

MockReviewProvider produces review text without contacting a model. The first Ctrl+C requests graceful cancellation; the second exits immediately.

  • The domain knows only ReviewStreamEvent and AbortSignal
  • The provider emits events; the CLI displays them
  • Tests use controlled time and no network
LESSON CHECK

Finish with evidence, not a feeling

After the Playground, run this check from the project root. It never contacts a model.

npm run verify:lesson -- M02