Async and streams
Async Is a Protocol, Not Magic
Predict execution order, then build a mock review tool that streams, times out, and cancels.
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.
What is await waiting for?
Write down the A–E order, run it, then move await and explain the change.
运行后显示诊断。
等待执行。
Need a hint?
Synchronous code runs first, Promise continuations are microtasks, and timers run later.
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.
async function start() {
try {
runReview(); // 没有 await,也没有 return
} catch (error) {
// 捕获不到 runReview 之后的 rejection
}
}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
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.
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
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