如何在请求调用时将值传递给回调函数?

发布于 2024-11-05 07:50:02 字数 329 浏览 0 评论 0原文

我有以下情况:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

新人笑 2024-11-12 07:50:02

你需要一个关闭。有比这更好的方法,但这应该清楚地展示这个概念:

var foo = [ 0, 1, 2 ]
for (var i in foo) {
    (function(i){
        Asyncstuff.get(URI).on('response', function(res) { console.log(i); } });
    })(i);
}

You need a closure. There are better ways than this, but this should clearly demonstrate the concept:

var foo = [ 0, 1, 2 ]
for (var i in foo) {
    (function(i){
        Asyncstuff.get(URI).on('response', function(res) { console.log(i); } });
    })(i);
}
┈┾☆殇 2024-11-12 07:50:02

正如 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.

且行且努力 2024-11-12 07:50:02

在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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文