Hi i have two JSON requests to make for a weather project, i need the data from the first request in order to personalise the second request for the user. My first request gets latitude and longitude of the user and the second needs those coordinates in the url for the current weather at that location.
var arrLocat = [];//users suburb, city, country, lat and lon
var userURL = "";//specific url tailored off users lat and lon
var userWeather = [];//current weather at users lat and lon
$(document).ready(function(){
//first JSON request
$.getJSON("http://ip-api.com/json", function (data){
arrLocat = data;
userURL = "http://api.openweathermap.org/data/2.5/weather?lat=" + arrLocat.lat + "&lon=" + arrLocat.lon + "&appid=61c4ebe6f40d2e2d7085e7c42d287e1d&units=metric";
console.log(arrLocat);THIS RETURNS FIRST, WORKS FINE
})
//second JSON request
.then(function(){
$.getJSON(userURL).done(function(index){
userWeather = index;
console.log(userWeather);//THIS RETURNS LAST, WORKS FINE BUT SHOULD RETURN SECOND
});
})
//do stuff here
.then(function(){
$("#locat").text(arrLocat.city + ", " + arrLocat.regionName + ", " + arrLocat.country);
console.log(userWeather);//THIS RETURNS BLANK GLOBAL VALUE, NOT CARRYING VALUE FROM SECOND .THEN FUNCTION ALSO SHOULD RETURN LAST NOT SECOND
})
});
I'm trying to run these in the order they are written, i understand that getJSON is asynchronous but i thought .then() was made to force order, to wait for the previous to complete before executing.
It took me a long while to figure out what was happening, it seems my final .then() is running before the second .then() JSON request. I'm new to deferred objects so i may be doing something fundamentally wrong that i'm not aware of?