美文网首页
koa2中间件原理

koa2中间件原理

作者: 万里独行采花贼 | 来源:发表于2019-01-31 03:00 被阅读0次

    源码:koa-compose.js

    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!')
      }
    
      /**
       * @param {Object} context
       * @return {Promise}
       * @api public
       */
    
      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)
          }
        }
      }
    }
    

    koa2的中间件流向是先按顺序执行next以前内容,然后对next以后内容进行回溯。
    middleware是使用use添加的中间件数组,
    核心代码只有一句Promise.resolve(fn(context, dispatch.bind(null, i + 1))); dispatch.bind(null, i + 1)替换掉了next,也就是说将所有的中间件以next占位符进行替换,类似于react setState的事务抽取机制

    相关文章

      网友评论

          本文标题:koa2中间件原理

          本文链接:https://www.haomeiwen.com/subject/gwghsqtx.html