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]);
}
}
所以我有这个函数来创建一个http.get请求,然后将响应抛出一个字符串数组。现在,当我调用该函数时,它工作正常,但是当我编写该函数时,(如下所示// makeRequest(url,index-2);),它不会影响strs []数组,即使一切我正在做的是在异步流程中(我认为)。有人能告诉我为什么会这样吗?