Learn canc.async and canc.await through a realistic checkout flow.
- Typed
yield* canc.await(): Each awaited step is visibly typed (TypeScriptsatisfiesshows result types inline). - Parallel steps with
canc.await.all: Charge and loyalty-points calls run concurrently; cancelling one cancels both. - Declared domain failure with
canc.throw:canc.throwyields a domain failure into the coroutine's typed failure set (such as aNegativeChargeErrorvalidation failure), keeping domain failures distinct from cancellation. - Cancel between steps: If the client cancels while payment is processing, the reservation is automatically released via a shielded
finallyblock. - Awaitable cancel:
await checkout.cancel()waits for cleanup to finish before returning. - Cancellation gap: the order confirmation email uses a legacy vendor call with no signal parameter. Once it starts it always finishes, in both flavors. The example marks the gap instead of hiding it.
E-commerce checkout flow: reserve stock, charge payment (plus accrue loyalty points), then send confirmation email. If canceled mid-payment, the reservation is released to free stock for other customers.
Build the monorepo first to generate /packages/*/dist:
cd ../.. # back to monorepo root
npm run buildThen enter the examples workspace:
cd examples/demo-coroutine
npm installShows the same checkout using native AbortSignal threading. Every step must check the signal after awaiting:
npm run start:vanillaLook for the comments marking signal-check sites. The vanilla version has 5 signal touchpoints vs. 0 in the canc version.
The same checkout using canc.async. Cancellation is ambient, no per-step checks:
npm run start:cancnpm run typechecknpm run testUse diff or a side-by-side viewer to see the mechanical differences:
diff src/checkout-vanilla.ts src/checkout-canc.ts
diff src/main-vanilla.ts src/main-canc.tsThe vanilla twin carries comments at every consequence point: "must remember to check the signal here" vs. the canc twin's "cancellation is ambient".
Stock reservation cleanup on cancel: The finally block in both flavors ensures the reservation is released. In the canc version, the finally block's yield* canc.await() call is shielded from further cancellation by the coroutine runtime. Cleanup proceeds even if cancel was requested. The vanilla version relies on AbortSignal semantics: within a finally block, the signal is already checked, and cleanup proceeds.
Cancellation gap: legacyConfirmEmail takes no signal at all, so it cannot be aborted by either flavor. It runs after the order is confirmed, so a stale email is the worst case. Not every operation can be made cancelable. The lesson is to notice the gap and judge whether it is acceptable, not to pretend it does not exist.
None in this example (src/lib not used). src/mock/checkout-ops.ts is scaffolding, not a copy target.
canc-promise and canc-coroutine are always live here. Feel free to copy this directory as a template.