简体   繁体   English

如何在node.js中将变量与异步回调同步

[英]How to sync variable with async callback in node.js

I have doubt in following code snippet. 我怀疑在下面的代码片段。

for(var i=0; i<5; i++){
    http.request(option, function(res){
        console.log(i)
    });
}

This prints value of 'i' as 5, five times. 这将'i'的值打印为5,五次。 Is there any way to make value of 'i' in sync with function(res) which can print 0,1,2,3,4 有没有办法让'i'的值与函数(res)同步,可以打印0,1,2,3,4

You have to give the variables the correct scope. 您必须为变量提供正确的范围。 Try something like this: 尝试这样的事情:

for(var i=0; i<5; i++){
    (function(key) {
        http.request(option, function(res){
            console.log(key)
        });
    })(i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM