koa2 compose

function compose (middleware) {
  // 检查输入有效性 确保输入为函数数组
  if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
  for (const fn of middleware) {
    if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
  }

  return function (context, next) {
    // last called middleware #
    let index = -1

    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      // 检测中间件有效性,为空时结束return Promise直接resolve
      // 此时流程就会往回执行
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      // 中间件有效,resolve一个function回溯调用关键
      try {
        return Promise.resolve(fn(context, function next () {
          // next()执行下一中间件
          return dispatch(i + 1)
        }))
      } catch (err) {
        return Promise.reject(err)
      }
    }
    return dispatch(0)
  }
}

var functionStack = [
  function foo (ctx, next) {
  console.log('foo1')
  next()
  console.log('foo2')
  },
  function bar (ctx, next) {
  console.log('bar1')
  next()
  console.log('bar2')
  },
  function qux (ctx, next) {
  console.log('qux1')
  next()
  console.log('qux2')
  }
 ]
 compose(functionStack)()

你可能感兴趣的:(koa2 compose)