题
首先...新年快乐!
您能给我解释一下,这是如何工作的? 我浏览了整个 连接((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);
}
);
请注意,这是一个非常简化的示例,功能中的参数较少。我也不改变 var
至 msg
自从 var
是一个保留的词。
其他提示
如果需要,请尝试使用异步模块。能够以串联,相似或使用池的方式运行的事情变得容易得多。
不隶属于 StackOverflow