If you're using JQuery then you could use a defer and promise. Something like this:
function getWeatherData(latitude, longitude) {
var temperature = 0;
var dfd = $.Deferred();
var url = "http://api.openweathermap.org/data/2.5/weather?lat=";
url += latitude;
url += "&lon=";
url += longitude;
url += "&cnt=1";
$.ajax({
type: "POST",
dataType: "jsonp",
url: url + "&callback=?",
async: false,
success: function (data) {
temperature = data.list[0].main.temp;
alert(temperature);
dfd.resolve(temperature);
},
error: function (errorData) {
alert("Error while getting weather data :: " + errorData.status);
}
});
return dfd.promise();
}
This will cause it to return the value once temperature has been resolved through the ajax call. I was using a weather API and had this same exact problem.