I'm having some troubles in making a HTTP request inside a loop.
Let me explain what I have....
I make an http GET to retrieve some values and then I need to make another HTTP GET for each couple of values that I've just taken from the first request.
The two calls are ok, and if I cut the for
cycle and try to run the whole request chain it works perfectly, but just one time since I removed the cycle. How can I make it work?
Here's the code:
request({
url: "some_url",
method: "GET",
json:true,
headers:[{'content-type': 'application/json'}]
}, function (error, response, body){
if(!error & response.statusCode === 200){
for(var i=0;i<body.length;i++){
for(var j=i;j<body.length-1;j++){
//if(i === body.length-1) return;
src = body[i].name;
dest = body[j+1].name;
console.log("sorgente ",sorg);
request({
url: "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+src+"&destinations="+dest,
method: "POST",
json:true,
headers:[{'content-type': 'application/json'}]
}, function (error, response, body){
if(!error & response.statusCode === 200){
console.log("TIME ",body.rows[0].elements[0].duration.text);
return;
}else{
console.log("google API failed!: ");
return;
}
});
}
}
}else{
console.log("/google_api failed!: ");
return;
}
});
I hope I was clear with the question.