Juggling ASYNC gives heapout of memory error

Juggling ASYNC gives heapout of memory error
0

#1

Can anyone please tell me why this code give JavaScript heap out of memory error?

var http = require('http');
var bl = require('bl');
var urls= [process.argv[2], process.argv[3], process.argv[4]];

var result=[];
for(var i=0; i<urls.length;){
	getData(urls[i], i, function(err,data){
		if(err){
			console.log(err);
		}
		if(data){			
			result[i] = data[0];
			i=data[1];
			if(i  === urls.length){
				console.log(result.join('\n'));
			}
			
		}	
		

	})
	
}
function getData(url,index, callback){
	var result="";
	
	http.get(url,function(response){
	     response.setEncoding('utf8');
		 response.on('data',function(data){
			 result+= data;
			 
		 })
		 response.on('err',function(err){
			 callback(err,null);
		 })
		 response.on('end',function(){
			  callback(null,[result, index++])
			 
		 })

	})

};

#2

First of all, let’s see if I understand this correctly.

You’re calling getData over and over again. If and when it brings back a result, you increase the value of i.

Is that correct?

If that is correct, then you’re potentially sending out thousands of http requests before the first one even comes back, no?


#3

I don’t intend to do so. I want to send request only when one result has come back.
And why would that make thousands of http request when I have not yet incremented the i ?


#4

Because the loop continues to be run over and over again until i is equal to or greater than urls.length.

The loop doesn’t wait until i is incremented to run the next iteration.

You can try it out with a simpler example:

var totalCalls = 0;
var j = 0;

for (var i = 0; i < 7;) {
  totalCalls++;
  if (j==2) {
    j -= 2;
    i++;
  } else {
    j++;
  }
}
console.log(totalCalls);

You will see from this example that even though i only gets incremented seven times, the actual loop runs 21 times.


#6

thank you for helping!