理解Koa洋葱模型

理解Koa洋葱模型

下面这段代码:

 const Koa = require("koa");
 const app = new Koa();
 app.use( (ctx, next) => {
   console.log(1);
    next();
   console.log(2);
 });
 app.use( (ctx, next) => {
   console.log(3);
    next();
   console.log(4);
 });
 app.use( (ctx, next) => {
   console.log(5);
    next();
   console.log(6);
 });
app.listen(3000);

按照正常的逻辑输出的是:1,2,3,4,5,6;但是实际输出的是:
1,
3,
5,
6,
4,
2,
下面我们就来理解如何实现这种输出。

1.首先定义用来存函数的数组middlewares(中间件),定义用来将函数存入数组的函数use

const app = {
  middlewares: [],// 用来存函数的数组
  use: function (fn) {
    this.middlewares.push(fn);
  }
}

2.执行use函数,开始将use中的实参(函数)存入数组middlewares中

app.use((next) => {
  console.log(1);
  next();
  console.log(2);
});
app.use((next) => {
  console.log(3);
  next();
  console.log(4);
});
app.use((next) => {
  console.log(5);
  next();
  console.log(6);
});

执行数组中的函数

// 定义compose函数
app.compose = function () {
  return function () {
    // 定义disPatch用来执行middlewares中的函数
    function disPatch(idx) {
      // 如果idx等于app.middlewares.length,则return掉
      if (idx === app.middlewares.length) {
        return;
      }
      // 从middlewares中取函数
      const fn = app.middlewares[idx];
      // 执行第一个app.use传入的实参(函数),并且传入实参next
      fn(function next() {
        disPatch(++idx);
      });
    }
    // 传入0,开始执行middlewares中的第一个函数,即执行app.use中传入的第一个函数
    disPatch(0);
  };
};
app.compose()();

执行顺序:

next函数即下一个app.use中传入的函数;
第三个app.use的next函数,会因为idx等于app.middlewares.length直接return掉;
当4执行完,则表示第一个app.use中next函数已执行完;
所以会往下执行,执行2,执行完2,所有代码全部执行完成,

比如你手里有一支牙签,横向穿过一个洋葱,是不是会层层穿透?从第一层进去、到第二层、第三次…然后到中间层后,再层层穿透的出,从第三层出、第二层、第一层…。就是koa的洋葱模型,一个执行顺序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值