0
var http=require('http');
var bl=require('bl');
var strs=[];
var finished=0;

for(var index=2; index<process.argv.length; index++)
{
    var url=process.argv[index];
    //makeRequest(url,index-2); --- This works.
    http.get(url,function (response)  //But if I do this inline, as opposed to making the request as a function, it goes to hell...why?
    {
        response.pipe
        (
            bl
            (
                function(err,data)
                {
                    if(err) throw err;
                    var thisResponse=data.toString();
                    strs[index-2]=thisResponse;  //this is not really happening...why?
                    finished++;
                    if(finished==3)
                    {
                        //it's getting here, but strs is unchanged from the beginning
                        printResults();
                    }
                }
            )
        );
    });
}


function makeRequest(url,index)
{
    http.get(url,function (response)
    {
        response.pipe
        (
            bl
            (
                function(err,data)
                {
                    if(err) throw err;
                    var thisResponse=data.toString();
                    strs[index]=thisResponse;
                    finished++;
                    if(finished==3)
                    {`enter code here`
                        printResults();
                    }
                }
            )
        );
    });
}


function printResults()
{
    for(var j=0; j<3; j++)
    {
        console.log(strs[j]);
    }
}

So I have this function to make an http.get request, and then throw the response in an array of strings. Now when I call the function, it works fine, but when I write the function out, (as seen below //makeRequest(url,index-2);), it doesn't affect the strs[ ] array, even though everything I'm doing is within the asynchronous flow (I think). Could somebody tell me why this is happening?

Monty Evans
  • 141
  • 1
  • 10
  • Because closure! `index` is (like `url`) no more a global variable inside the `makeRequest` function – Bergi Apr 08 '16 at 11:43
  • Question was closed while I was posting my asnwer, so I will post it here, hope it helps you understand the issue. Your inline code is referencing the "index" variable that you create in your "for" statement. By the time that you have got the response to your http request, the whole loop has finished, and therefore, the index variable which you code is referencing will have a value higher than what you're expecting. If you call a different function, the parameter "index", will keep the value you called your function with. – Ruben Serrate Apr 08 '16 at 11:47
  • @RubenSerrate thanks, that makes a lot of sense. – Monty Evans Apr 08 '16 at 13:03

0 Answers0