Compose Async Middleware
Hard · Async
Write compose(middlewares) that chains async middleware onion-style (like Koa) into one (ctx) => Promise<void> function.
- The composed function runs the first middleware with ctx and a next function. next() runs the rest of the chain and resolves when it has finished, so code after await next() runs on the way back out.
- next() of the last middleware resolves right away. A middleware that never calls next ends the chain.
- Calling next() twice in the same middleware returns a promise rejected with Error("next() called multiple times") and runs nothing.
- Errors travel back up to whoever awaited next(), then to the caller of the composed function. No middleware: resolve right away.
The driver runPipeline(stack) builds middleware from lists of steps and returns the log and the final error (or null).