大前端刷级之路koa及相关库源码解读Node.js

解读koa-compose

2018-05-09  本文已影响11人  天驱丶

上一讲我们讲到 koa-router 的实现,今天我们讲讲 koa-compose,compose是将多个函数合并成一个函数(形如: g() + h() => g(h())),koa-compose则是将 koa/koa-router 各个中间件合并执行,结合 next() 就形成了洋葱式模型

image

有同学可能不了解为何是洋葱式模型,接下来我们改造下官方test用例,打出相应 log 应该就清楚了

it.only('should work', async () => {
    const arr = []
    const stack = []

    stack.push(async (context, next) => {
      arr.push(1)
      await wait(1)
      console.log(1)
      await next()
      console.log(1, 1)
      await wait(1)
      arr.push(6)
    })

    stack.push(async (context, next) => {
      arr.push(2)
      await wait(1)
      console.log(2)
      await next()
      console.log(2, 2)
      await wait(1)
      arr.push(5)
    })

    stack.push(async (context, next) => {
      arr.push(3)
      await wait(1)
      console.log(3)
      await next()
      console.log(3, 3)
      await wait(1)
      arr.push(4)
    })
    const a = compose(stack)
    console.log('result-->>>>>>', a)
    await compose(stack)({})
    expect(arr).toEqual(expect.arrayContaining([1, 2, 3, 4, 5, 6]))
  })

结果是1, 2, 3, 33, 22, 11,可以看出先按顺序执行 stack 数组中每个中间件 next 前的代码,之后倒序执行 next 后的代码,相当于一根牙签横穿洋葱,先从外到内,再从内到外,所以叫做洋葱模型。

koa-compose 的代码只有不够50行,细读确实是一段很精妙的代码,而实际核心代码则是这一段:

return function (context, next) {
    // last called middleware #
    let index = -1
    return dispatch(0)
    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        return Promise.resolve(fn(context, function next () {
          return dispatch(i + 1)
        }))
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }

虽然短,但是之中使用了4层 return,初看会比较绕,我们只看第3,4层 return,这是返回实际的执行代码链

return Promise.resolve(fn(context, function next () {
          return dispatch(i + 1)
        }))

以下分解参照跨入Koa2.0,从Compose开始这篇文章,说得挺好的。

这里尝试用3个中间件进行 compose,并逐步分解执行过程
Promise.resolve(function(context, next){
    //中间件一第一部分代码
    await/yield next();
    //中间件一第二部分代码
}());

很明显这里的next指向dispatch(1),那么就进入了第二个中间件;

Promise.resolve(function(context, 中间件2){
    //中间件一第一部分代码
    await/yield Promise.resolve(function(context, next){
        //中间件二第一部分代码
        await/yield next();
        //中间件二第二部分代码
    }())
    //中间件一第二部分代码
}());

很明显这里的next指向dispatch(2),那么就进入了第三个中间件;

Promise.resolve(function(context, 中间件2){
    //中间件一第一部分代码
    await/yield Promise.resolve(function(context, 中间件3){
        //中间件二第一部分代码
        await/yield Promise(function(context){
            //中间件三代码
        }());
        //中间件二第二部分代码
    })
    //中间件一第二部分代码
}());

此时中间件三代码执行完毕,开始执行中间件二第二部分代码,执行完毕,开始执行中间一第二部分代码,执行完毕,所有中间件加载完毕。

总结

koa-compose 巧妙的运用了 compose 的特性,结合 async await 中 next 的等待执行,形成了洋葱模型,我们可以利用这一特性在 next 之前对 request 进行处理,而在 next 之后对 response 进行处理(例如 error 处理)

上一篇下一篇

猜你喜欢

热点阅读