0

ok am starting on nodeJS and am stuck at this code, if i output inside the loop i get the array as i want, but if i do outside the loop it returns undefined.

question is: What is wrong with this?, thx in advance;

var array = [];
var temp = "";

var http = require("http");

for (var i = 2; i < 5; i++) {
    http.get(process.argv[i],function(res){
        res.setEncoding("utf8");
        res.on("data",function(data){
            temp += data;
        });
        res.on("end", function(){

            array.push(temp);
            console.log(array[0]);//this returns the array[0] OK NP;
            temp = "";
        });}

    );

}
console.log(array[0]);//this returns undefined;
Tymofek
  • 15
  • 4

3 Answers3

2

It's because the code is asynchronous and when you call console.log outside of the http request not yet finshed so the array[0] is undefined.

jcubic
  • 61,973
  • 54
  • 229
  • 402
1

It's because "console.log" is being run before "array.push". This is because array.push happens at the end of the response, and since node.js follows event based programming, the array.push only happens when the end of the response is triggered. Console.log happens before res.on "end" gets triggered.

user3587754
  • 831
  • 2
  • 7
  • 20
0

In your code you are basically launching 3 calls to 3 destinations and then printing the contents of the array before getting any response.

If you want to print the resoults after all three calls has been completed you may use a counter, init it at 0 before the loop and increase it by one before any http call. Then, in the end event decrease the counter by 1 and if the counter has reached 0 print the array or do any other stuff you want.

Hope this helps

Leo Nomdedeu
  • 338
  • 2
  • 5