1

Working with NodeJS calling to an HTTP API I encountered a weird behavior. I had an API call which returns an array of IDs, and on each of those IDs I needed to make another HTTP request with the ID as the parameter. I ended up with this code:

http.get("/getPersons", function(persons) {
    for(var i = 0; i < persons.length; i++) {
        var count = 0;

        http.get("/getPersonAddress?id=" + persons[i].id, function(address) {
            persons[i].address = address;
            count++;

            if(count == persons.length) {
                res.end(JSON.stringify(persons));
            }
        });
    }
});

Now since the loop finishes before all of the HTTP requests received a response, i will be equal persons.length + 1, and it looks like that i variable passed to the callback function is passed by reference and not by value because when I run this code it complains that persons[i].address is undefined, and when I look at i at this moment I see it equals persons.length + 1 instead of the value of i in the moment http.get gets called.

How would you normally solve this?

UnTraDe
  • 3,747
  • 10
  • 36
  • 60

0 Answers0