如何在请求调用时将值传递给回调函数?
我有以下情况:
var foo = [ 0, 1, 2 ]
for (var i in foo) {
Asyncstuff.get(URI).on('response', function(res) { console.log(i); } });
}
因为 .on('response',...) 是以异步方式调用的,所以输出很可能是
2
2
2
Is There a a possible to pass the value of i at .get() 被调用到回调函数的时间?
I have the following situation:
var foo = [ 0, 1, 2 ]
for (var i in foo) {
Asyncstuff.get(URI).on('response', function(res) { console.log(i); } });
}
Because the .on('response',...) is called in an asynchronous manner, the output will most likely be
2
2
2
Is there a possibility to pass the value of i at the time the .get() is called to the callback function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你需要一个关闭。有比这更好的方法,但这应该清楚地展示这个概念:
You need a closure. There are better ways than this, but this should clearly demonstrate the concept:
正如 cwolves 提到的,你需要使用闭包来包装它。原因是在 JavaScript 和其他一些语言(例如:C#)中,闭包捕获“变量”而不是“值”,因此在代码中,变量“i”被内部函数捕获,并且当该函数执行时,它使用捕获的值。变量“i”显然将是循环结束时循环中的最后一个值。在 JavaScript 等捕获变量的语言中使用闭包时需要小心。
在 cwolves 解决方案中,函数内的“i”成为一个新变量,与 for 循环中的 I 不同,因此它工作正常。
As cwolves has mentioned you need to wrap it using closure. The reason for that is in JavaScript and some other languages (ex: C#) closure capture "variables" and not "values" hence in your code the variable "i" is captured by the inner function and when that function executes it uses the captured variable "i" which obviously will be last value in the loop as the loop ends. You need to be careful when you use closures in languages such as JavaScript which captures variables.
In cwolves solution the "i" inside the function becomes a new variable and is not same as the I in the for loop and hence it works fine.
在node.js中使用递归模式循环
请参阅我的回答是,我确信您可以使用它来解决您的问题,因为您可以控制 for 循环
Using recursive pattern loop with node.js
please refer my answer , am sure you can use this to solve your problem as you have the control over for loop