高级前端手写代码【Q625】简述 koa 的中间件原理,手写 koa-compose 代码

简述 koa 的中间件原理,手写 koa-compose 代码

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 643

Author 回答者: shfshanyue

function compose(middlewares) {
  return (ctx) => {
    const dispatch = (i) => {
      const middleware = middlewares[i];
      if (i === middlewares.length) {
        return;
      }
      return middleware(ctx, () => dispatch(i + 1));
    };
    return dispatch(0);
  };
}

Author 回答者: haotie1990

const middlewares = [];
 
middlewares.push(async function (ctx, next) {
  console.log("1");
  await next();
  console.log("6");
});
 
middlewares.push(async function (ctx, next) {
  console.log("2");
  await next();
  console.log("5");
});
 
middlewares.push(async function (ctx, next) {
  console.log("3");
  await next();
  console.log("4");
});
 
async function run() {
  const middleware = middlewares.shift();
  await (middleware && middleware({}, run));
}
 
run(); // expect output: 1 2 3 4 5 6

Author 回答者: shfshanyue

@haotie1990 你这种实现,简洁多了!

Author 回答者: Asarua

这个好棒