1

您能否向我解释一下,串行执行功能是如何工作的?
我浏览了Connect 的源代码,但我不明白。

我想自己写。

app.get(
  '/',
  function(req, res, next) {
    // Set variable        
    req.var = 'Happy new year!';
    // Go to next function
    next();
  },
  function(req, res, next) {
    // Returns 'Happy new year!' 
    console.log(req.var); // <- HOW IS THIS POSSIBLE?
    // (...)
  }      
);
4

2 回答 2

2

如果需要,请尝试使用异步模块。能够串联、并行运行或使用池使事情变得更容易。

https://github.com/caolan/async

于 2011-12-24T00:34:34.673 回答
2

看起来好像您提供的第一个函数参数首先被get()函数调用。

调用时,会为调用提供 3 个参数。在调用内部,req参数必须是您可以为其分配属性的对象。您已经分配了该var属性,并为其赋予了'Happy new year!'.

您传递的下一个函数参数是通过对参数的调用来调用的next(),并且再次为调用提供了 3 个参数。第一个参数显然与您分配var属性的第一个调用相同的对象。

因为它(显然)是同一个对象,所以您分配的属性仍然存在。

这是一个简单的例子:http: //jsfiddle.net/dWfRv/1/ (打开你的控制台)

// The main get() function. It has two function parameters.
function get(fn1, fn2) {
      // create an empty object that is passed as argument to both functions.
    var obj = {};
      // create a function that is passed to the first function, 
      //   which calls the second, passing it the "obj".
    var nxt = function() {
        fn2(obj); //When the first function calls this function, it fires the second.
    };
      // Call the first function, passing the "obj" and "nxt" as arguments.
    fn1(obj, nxt);
}

// Call get(), giving it two functions as parameters
get(
  function(req, next) {
      // the first function sets the req argument (which was the "obj" that was passed).
    req.msg = 'Happy new year';
      // the second function calls the next argument (which was the "nxt" function passed).
    next();
  }, 
  function(req) {
     // The second function was called by the first via "nxt",
     //   and was given the same object as the first function as the first parameter,
     //   so it still has the "msg" that you set on it.
    console.log(req.msg);
  }
);

请注意,这是一个非常简化的示例,函数中的参数较少。也不是我改成var因为msgvar保留字。

于 2011-01-01T21:12:52.237 回答