Something wrong with API request inside a loop

265 Views Asked by At

I'm in big trouble,I can't understand why this thing does not work.I need to make an API request for each value of an array,and if I look in my console javascript,the request are served but I need latitude and longitude value inside the request.The problem is that outside the API request I have 4 values (2 lat and long for each element of the array),and inside the API request I find only the last two lat and long,why?It seems really no sense and I don't know where the problem may be.Here is the code

var luoghi = {"city":[
                    { "lat":"45.46" , "lng":"9.19" , "name":"Milano" },
                    { "lat":"41.12" , "lng":"16.86" , "name":"Bari" }
            ]}; 
var arr=[];
for(var i in luoghi.city){  
lat = luoghi.city[i].lat;
lng= luoghi.city[i].lng;

console.log("Before API request "+lat+" "+lng);//here i have the right 4 values

var wUnderAPI = "http://api.wunderground.com/api/"+API_WU+"/forecast/q/"+lat+","+lng+".json?callback=?";
$.getJSON( wUnderAPI, {format: "json"}).done(function( data ) {
    if(typeof data['forecast']['simpleforecast']['forecastday'] != 'undefined'){  // controllo esito richiesta json
            console.log(" Inside the request "+lat+" "+lng); //here just the bari lat & lng 
    }
});
}

The API_WU is my private API KEY,but since it is for a not commercial use,anyone can get one from the site.Hope my question was clear,because is a problem that it's hard even to explain :) thanks in advance.

1

There are 1 best solutions below

2
On

Your done function references the lat,lng defined previously and since it is aynchronous, e.g. it can take some time to return and does not block the script carrying on in the loop, it will always give you the last defined values as it most likely only returns after all other values have been processed. You will need to feed the correct data to the callback in the done function.

try passing the lat and lng as arguments to the done

$.getJSON( wUnderAPI, {format: "json"}).done(function( data, lat, lng ) {
    if(typeof data['forecast']['simpleforecast']['forecastday'] != 'undefined'){  // controllo esito richiesta json
            console.log(" Inside the request "+lat+" "+lng); //here just the bari lat & lng 
    }
});