Koa compose原理

505 阅读1分钟

let app = {};
app.middlewares = [];
app.use = function (fn) {
  this.middlewares.push(fn);
}
// reduce  
app.use(async (next) => {
  console.log(1);
  //这里的next 相当于 传入的() => dispatch(index+1)
  await next();//koa中写了next一定要写await
  console.log(3);
})
app.use((next) => {
  console.log(2)
  //next()
  console.log(4);
});
// app.use((next) => {
//   console.log(5)
//   next()
//   console.log(6);
// });
function dispatch(index){
  if (index === app.middlewares.length) return;
  let middle = app.middlewares[index]; // 默认调用第一个
  // 将第二个数组中的方法传入
  // () => dispatch(index+1)相当于传入参数next
  middle(() => dispatch(index+1)); // ()=>{}=>next函数

  /**
   * 第一次执行的时候 dispatch(0) 此时第一个app.middlewares[0]是
   * app.use(async (next) => {}此时next是参数,因此
   * (next) => { 第一个middle
     console.log(1); 2
     next();
     console.log(3); 4
    }
    然后执行 middle(() => dispatch(index+1)) 此时传入的next 就是 () => dispatch(index+1)
    打印console.log(1) 然后next()执行 相当于 执行 dispatch函数
    取到第二个中间件  也就是
    (next) => { 第二个middle
     console.log(2); 
     console.log(4);
    }
   * 打印2,4 执行完打印3
   */
}
dispatch(0);
//1 2 5 6 4 3