shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.94k stars 510 forks source link

【Q625】简述 koa 的中间件原理,手写 koa-compose 代码 #643

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago
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)
  }
}
haotie1990 commented 3 years ago

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
shfshanyue commented 3 years ago

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

Asarua commented 3 years ago

这个好棒