koa的洋葱设计模型

async function a(ctx, next) { console.log("invoke a") await next() console.log("exit a") } async function b(ctx, next) { console.log("invoke b") await next() console.log("exit b") } function compose(middleware) { return (ctx, next) => { let index = -1 async function dispatch(i) { if (i <= index) { throw new Error('next() called multiple times') } index = i let fn = middleware[i] if (i === middleware.length) { fn = next } if (!fn) { return } return await fn(ctx, () => { return dispatch(i + 1) }) } return dispatch(0) } } let func = compose([a, b]) func('context', () => { console....

June 5, 2020 · 1 min · Theme PaperMod