串联执行函数
您能否向我解释一下,串行执行函数是如何工作的?
我浏览了 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?
// (...)
}
);
Could you please explain to me, how does executing functions in series works?
I browsed throught Connect's source code, but I don't get it.
I would like to write it by myself.
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?
// (...)
}
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来好像您提供的第一个函数参数首先被
get()
函数调用。调用时,会向调用提供 3 个参数。在调用内部,
req
参数必须是可以为其分配属性的对象。您已分配var
属性,并为其指定值'Happy new Year!'
。您传递的下一个函数参数是通过调用
next()
参数来调用的,并且再次向该调用提供 3 个参数。第一个参数显然与分配给var
属性的第一次调用的对象相同。因为它(显然)是同一个对象,所以您分配的属性仍然存在。
这是一个简单的示例: http://jsfiddle.net/dWfRv/1/ (open您的控制台)
请注意,这是一个非常简化的示例,函数中的参数较少。也不是因为
var
是保留字,所以我将var
更改为msg
。It appears as though the first function argument you provide gets called by the
get()
function first.When it is called, 3 parameters are provided to the call. Inside the call, the
req
parameter must be an object to which you can assign properties. You've assigned thevar
property, and given it a value of'Happy new year!'
.The next function argument you pass is called via a call to the
next()
parameter, and 3 parameters are again provided to the call. The first parameter is apparently the same object that was given to the first call where you assigned thevar
property.Because it is (apparently) the same object, the property you assigned is still present.
Here's a simple example: http://jsfiddle.net/dWfRv/1/ (open your console)
Note that this is a very simplified example, with fewer parameters in the functions. Not also that I changed
var
tomsg
sincevar
is a reserved word.如果需要,请尝试使用异步模块。它使能够串联、并联运行或使用池变得更加容易。
https://github.com/caolan/async
If you want, try using the async module. It makes thing much easier to be able to run in series, parallels or use a pool.
https://github.com/caolan/async