koa原理详解

文章不易,请关注公众号 毛毛虫的小小蜡笔,多多支持,谢谢

先看个Demo

app.use(async (ctx, next) => {
  console.log(1)
  await next()
  console.log(2)
  ctx.body = 'Hello Koa';
});
app.use(async (ctx, next) => {
  console.log(3)
  await next()
  console.log(4)
});
app.use(async (ctx, next) => {
  console.log(5)
});

输出结果是:
1
3
5
4
2

这就是所谓的洋葱模型。
第一个中间件在最外层,然后第二个在第二层,第三个则是最里面一层。
所以先执行1,然后到第二层的3,再到最里面的5,执行完后再到第二层的4,最后返回到第一层的2。

看源码

app.use最主要的是把中间件存起来:this.middleware.push(fn)。

 

详情 请查看:毛毛虫的小小蜡笔

 

posted @ 2022-05-31 17:07  simonbaker  阅读(45)  评论(0编辑  收藏  举报