中间件执行机制
简单实现 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);