傻瓜式解讀koa中介軟體處理模組koa-compose

若邪發表於2018-10-29

最近需要單獨使用到koa-compose這個模組,雖然使用koa的時候大致知道中介軟體的執行流程,但是沒仔細研究過原始碼用起來還是不放心(主要是這個模組程式碼少,多的話也沒興趣去研究了)。

koa-compose看起來程式碼少,但是確實繞。閉包,遞迴,Promise。。。看了一遍腦子裡繞不清楚。看了網上幾篇解讀文章,都是針對單行程式碼做解釋,還是繞不清楚。最後只好採取一種傻瓜的方式:

koa-compose去掉一些註釋,型別校驗後,原始碼如下:

function compose (middleware) {
  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, dispatch.bind(null, i + 1)));
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}
複製程式碼

寫出如下程式碼:

var index = -1;
function compose() {
    return dispatch(0)
}
function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      var fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve('fn is undefined')
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
      } catch (err) {
        return Promise.reject(err)
      }
 }
 
 function f1(context,next){
    console.log('middleware 1');
    next().then(data=>console.log(data));
    console.log('middleware 1');
    return 'middleware 1 return';
  }
  function f2(context,next){
    console.log('middleware 2');
    next().then(data=>console.log(data));
    console.log('middleware 2');
    return 'middleware 2 return';
  }
  function f3(context,next){
    console.log('middleware 3');
    next().then(data=>console.log(data));
    console.log('middleware 3');
    return 'middleware 3 return';
  }
var middleware=[
  f1,f2,f3
]

var context={};
var next=function(context,next){
    console.log('middleware 4');
    next().then(data=>console.log(data));
    console.log('middleware 4');
    return 'middleware 4 return';
};
compose().then(data=>console.log(data));
複製程式碼

直接執行結果如下:

"middleware 1"

"middleware 2"

"middleware 3"

"middleware 4"

"middleware 4"

"middleware 3"

"middleware 2"

"middleware 1"

"fn is undefined"

"middleware 4 return"

"middleware 3 return"

"middleware 2 return"

"middleware 1 return"

按著程式碼執行流程一步步分析:

dispatch(0)

i==0,index==-1 i>index 往下

index=0

fn=f1

Promise.resolve(f1(context, dispatch.bind(null, 0 + 1)))

這就會執行

f1(context, dispatch.bind(null, 0 + 1))

進入到f1執行上下文

console.log('middleware 1');

輸出middleware 1

next()

其實就是呼叫dispatch(1) bind的功勞

遞迴開始

dispatch(1)

i==1,index==0 i>index 往下

index=1

fn=f2

Promise.resolve(f2(context, dispatch.bind(null, 1 + 1)))

這就會執行

f2(context, dispatch.bind(null, 1 + 1))

進入到f2執行上下文

console.log('middleware 2');

輸出middleware 2

next()

其實就是呼叫dispatch(2)

接著遞迴

dispatch(2)

i==2,index==1 i>index 往下

index=2

fn=f3

Promise.resolve(f3(context, dispatch.bind(null, 2 + 1)))

這就會執行

f3(context, dispatch.bind(null, 2 + 1))

進入到f3執行上下文

console.log('middleware 3');

輸出middleware 3

next()

其實就是呼叫dispatch(3)

接著遞迴

dispatch(3)

i==3,index==2 i>index 往下

index=3

i === middleware.length

fn=next

Promise.resolve(next(context, dispatch.bind(null, 3 + 1)))

這就會執行

next(context, dispatch.bind(null, 3 + 1))

進入到next執行上下文

console.log('middleware 4');

輸出middleware 4

next()

其實就是呼叫dispatch(4)

接著遞迴

dispatch(4)

i==4,index==3 i>index 往下

index=4

fn=middleware[4]

fn=undefined

reuturn Promise.resolve('fn is undefined')

回到next執行上下文

console.log('middleware 4');

輸出middleware 4

return 'middleware 4 return'

Promise.resolve('middleware 4 return')

回到f3執行上下文

console.log('middleware 3');

輸出middleware 3

return 'middleware 3 return'

Promise.resolve('middleware 3 return')

回到f2執行上下文

console.log('middleware 2');

輸出middleware 2

return 'middleware 2 return'

Promise.resolve('middleware 2 return')

回到f1執行上下文

console.log('middleware 1');

輸出middleware 1

return 'middleware 1 return'

Promise.resolve('middleware 1 return')

回到全域性上下文

至此已經輸出

"middleware 1"

"middleware 2"

"middleware 3"

"middleware 4"

"middleware 4"

"middleware 3"

"middleware 2"

"middleware 1"

那麼

"fn is undefined"

"middleware 4 return"

"middleware 3 return"

"middleware 2 return"

"middleware 1 return"

怎麼來的呢

回頭看一下,每個中介軟體裡都有

next().then(data=>console.log(data));

按照之前的分析,then裡最先拿到結果的應該是next中介軟體的,而且結果就是Promise.resolve('fn is undefined')的結果,然後分別是f4,f3,f2,f1。那麼為什麼都是最後才輸出呢?

Promise.resolve('fn is undefined').then(data=>console.log(data));
console.log('middleware 4');
複製程式碼

執行一下就清楚了

或者

setTimeout(()=>console.log('fn is undefined'),0);
console.log('middleware 4');
複製程式碼

整個呼叫過程還可以看成是這樣的:

function composeDetail(){
  return Promise.resolve(
    f1(context,function(){
      return Promise.resolve(
        f2(context,function(){
          return Promise.resolve(
            f3(context,function(){
              return Promise.resolve(
                next(context,function(){
                  return Promise.resolve('fn is undefined')
                })
              )
            })
          )
        })
      )
    })
  )
}
composeDetail().then(data=>console.log(data));
複製程式碼

方法雖蠢,但是compose的作用不言而喻了

最後,if (i <= index) return Promise.reject(new Error('next() called multiple times'))這句程式碼何時回其作用呢?

一箇中介軟體裡呼叫兩次next(),按照上面的套路走,相信很快就明白了。

相關文章