执行串联function

首先…新年快乐!

你能不能请我解释一下,这是如何工作的? 我浏览了Connect的( https://github.com/senchalabs/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? // (...) } ); 

提前致谢!

看起来好像你提供的第一个函数参数被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); } ); 

请注意,这是一个非常简单的例子,function中的参数更less。 不仅如此,因为var是保留字,所以我将var更改为msg

如果你想,尝试使用asynchronous模块。 它使事情变得更容易,能够串联,相似或使用游泳池。

https://github.com/caolan/async