JavaScript中对循环语句的优化技巧深入探讨(6)

// Check the route
      if (check.test(url)) {
        try {
          function later() {
            debug('A middleware says it need to be later on %s', url);
            // The dependencies do not right now
            if (middlewares.indexOf(curr) !== middlewares.length - 1) {
              _later(curr);
              index--;
              next();
            } else {
              debug('A middleware dependencies wrong');

// This middleware can not run
              out();
            }
          }

// Run the middleware
          if (utils.isFunc(curr.handler)) {

// Normal middleware function
            curr.handler(req, res, next, later);

} else if (utils.isObject(curr.handler) && utils.isFunc(curr.handler.emit)) {

// Server object
            curr.handler.emit('request', req, res, next, later);

} else {

// There are something wrong about the middleware
            next();

}
        } catch(err) {
          next();
        }
      } else {
        next();
      }
    } else {
      // Out to next step of the pipeline
      out();
    }
  }

// if the middleware depend on other middlewares,
  // it can let it later to run
  function _later(curr) {
    var i = middlewares.indexOf(curr);
    var _tmp1 = middlewares.slice(0, i);
    _tmp1.push(middlewares[i + 1], curr);
    var _tmp2 = middlewares.slice(i + 2);
    [].push.apply(_tmp1, _tmp2);
    middlewares = _tmp1;
  }

// first middleware
  next();

return this;
};

虽然这段代码看上去狠复杂,不过如果我们对其精简之后,就清晰许多了。

复制代码 代码如下:


server.runMiddlewares = function(url, req, res, out) {
  var index = -1;

var middlewares = this._usingMiddlewares;

// run the next middleware if it is exists
  function next(err) {
    index++;

// current middleware
    var curr = middlewares[index];

if (curr) {
      var check = new RegExp(curr.route);

// Check the route
      if (check.test(url)) {
          // run the current middleware
          curr.handler(req, res, next);
      } else {
        next();
      }
    } else {
      // Out to next step of the pipeline
      out();
    }
  }

// first middleware
  next();

return this;
};

递归之所以可以用於中间件系统的实现,是因为递归是最适合 node.js 中异步 i/o 的程序流程响应方式。

在这段中间件实现代码中,this._usingmiddlewares为循环数组,function next()是循环体,其中check.test(url)为执行判断条件, 而循环处理代码就是循环体中最前面的index计数器自增 1 和next函数自身的递归调用。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgpjgz.html