跳到主要内容

中间件执行机制

简单实现 Koa 洋葱模型

// 核心函数
function compose (middleares) {
+ let index = -1; 创建指针
// 准备遍历
function dispatch(i) {
+ if(i <= index) throw new Error('next() called multiple times');
+ index = i;
if(i === middleares.length) return;
const middleare = middleares[i]; // 别忘记中间件的格式 (ctx, next) => ()
return middleare('ctx', dispatch.bind(null, i + 1)); // 每次调用next,都用调用一次dispatch方法,并且i+1,
}
return dispatch(0)
}

...

app.use((ctx, next) => {
console.log("1");
next();
+ next();
console.log('2');
})
app.use((ctx, next) => {
console.log("3");
next();
console.log('4');
})

app.listen(3000);

参考

https://juejin.cn/post/7202801134557069373

https://juejin.cn/post/7033642487898079240#comment

网站备案:蜀ICP备2023001425号👏 Powered By Docusaurus, Semi Design