Skip to content

Do-notation with generators

Relay’s intake has four steps, and each can fail: parse the body, find the route for the source, check the payload size, build the job. Last lesson gave you flatMap to chain them. It works, but look at what happens when a later step needs a value from an earlier one.

The job needs parsed, queue and payload, from three different steps. A callback can only see the names in scope, so every step has to nest inside the previous callback:

type Result<A, E> =
| { readonly ok: true; readonly value: A }
| { readonly ok: false; readonly error: E }
declare const flatMap: <A, B, F>(f: (a: A) => Result<B, F>) => <E>(r: Result<A, E>) => Result<B, E | F>
declare const ok: <A>(a: A) => Result<A, never>
declare function parse(body: string): Result<{ readonly kind: string; readonly payload: string }, "ParseError">
declare function findRoute(source: string): Result<string, "NoRoute">
declare function checkSize(payload: string): Result<string, "TooLarge">
const intake = (source: string, body: string) =>
flatMap((parsed: { readonly kind: string; readonly payload: string }) =>
flatMap((queue: string) =>
flatMap((payload: string) => ok({ queue, kind: parsed.kind, payload }))(checkSize(parsed.payload)),
)(findRoute(source)),
)(parse(body))

Each step adds an indent and a closing parenthesis at the end, far from where it opened. Adding a fifth step means editing the innermost line and the end of the chain. The shape of the code no longer matches the shape of the steps, which are just “do this, then this”.

Generators can pause. A generator function can yield* to another generator and receive its return value. Use that to write each step as one line:

type Err<E> = { readonly ok: false; readonly error: E }
type Result<A, E> = { readonly ok: true; readonly value: A } | Err<E>
function* unwrap<A, E>(r: Result<A, E>): Generator<Err<E>, A, unknown> {
if (r.ok) return r.value
yield r
throw new Error("unreachable: gen never resumes a failed block")
}

unwrap returns the value of a successful Result, so const x = yield* unwrap(r) reads like “x is the success of r”. For a failed one it yields the failure and stops. Its type says the same: it can yield an Err<E>, and it returns an A.

The throw after the yield satisfies the return type. It is never reached, because the runner below never resumes a block that yielded.

gen takes a generator function and runs it once:

type Err<E> = { readonly ok: false; readonly error: E }
type Result<A, E> = { readonly ok: true; readonly value: A } | Err<E>
type ErrorOf<Y> = Y extends Err<infer E> ? E : never
declare const ok: <A>(a: A) => Result<A, never>
export function gen<Y extends Err<unknown>, A>(body: () => Generator<Y, A, unknown>): Result<A, ErrorOf<Y>>
export function gen(body: () => Generator<Err<unknown>, unknown, unknown>): Result<unknown, unknown> {
const it = body()
const step = it.next()
if (step.done) return ok(step.value)
it.return(undefined) // run finally blocks in the abandoned block
return step.value
}

Successful unwraps never yield, so the first next() runs the block until it returns, or until the first failure yields. That is the early return. step.value is then the failed Result itself, and the rest of the block never runs. Calling it.return makes any finally blocks run, so cleanup is not skipped.

The two signatures are the overload trick from M4: callers see the precise first one, and the second is loose enough to implement without a cast.

Now the intake reads in the order it runs:

type Err<E> = { readonly ok: false; readonly error: E }
type Result<A, E> = { readonly ok: true; readonly value: A } | Err<E>
type ErrorOf<Y> = Y extends Err<infer E> ? E : never
declare function unwrap<A, E>(r: Result<A, E>): Generator<Err<E>, A, unknown>
declare function gen<Y extends Err<unknown>, A>(body: () => Generator<Y, A, unknown>): Result<A, ErrorOf<Y>>
declare function parse(body: string): Result<{ readonly kind: string; readonly payload: string }, "ParseError">
declare function findRoute(source: string): Result<string, "NoRoute">
declare function checkSize(payload: string): Result<string, "TooLarge">
const intake = (source: string, body: string) =>
gen(function* () {
const parsed = yield* unwrap(parse(body))
const queue = yield* unwrap(findRoute(source))
const payload = yield* unwrap(checkSize(parsed.payload))
return { queue, kind: parsed.kind, payload }
})

parsed, queue and payload are all in scope at the end, and there is one line per step. If findRoute fails, checkSize never runs, which is the same behavior as the flatMap chain.

You never write the error type of intake. TypeScript infers the type of everything the block yields, which is the union of every Err<E> from every unwrap. ErrorOf pulls the E out of each member:

type Err<E> = { readonly ok: false; readonly error: E }
type Result<A, E> = { readonly ok: true; readonly value: A } | Err<E>
type ErrorOf<Y> = Y extends Err<infer E> ? E : never
declare function unwrap<A, E>(r: Result<A, E>): Generator<Err<E>, A, unknown>
declare function gen<Y extends Err<unknown>, A>(body: () => Generator<Y, A, unknown>): Result<A, ErrorOf<Y>>
declare const a: Result<number, "A">
declare const b: Result<string, "B">
const both = gen(function* () {
const x = yield* unwrap(a)
const y = yield* unwrap(b)
return { x, y }
})
// Result<{ x: number; y: string }, "A" | "B">

ErrorOf<Y> is a conditional type that distributes over the union, so Err<"A"> | Err<"B"> becomes "A" | "B". Add a step that can fail with "C" and the result type grows to include "C". Nothing else in the block changes.

Implement unwrap, gen and handle. The flatMap version (handleWithFlatMap) is given, and your handle must behave the same, including which error wins when several steps would fail.

  • flatMap chains nest because a later step can only see names from enclosing callbacks.
  • yield* on unwrap(result) gives the success value, or yields the failure and stops the block.
  • gen calls next() once: a return means ok, a yield means the first failure, and the rest of the block is skipped.
  • The error type is the union of every yielded Err<E>, inferred through ErrorOf.
  • The generator never resumes after a failure, so the runner needs no cast: the overload keeps the precise type for callers.