Gaurav
Gaurav

Reputation: 788

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. Is there any way to make value of 'i' in sync with function(res) which can print 0,1,2,3,4

Upvotes: 0

Views: 700

Answers (1)

Adam Brill
Adam Brill

Reputation: 330

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);
}

Upvotes: 2

Related Questions