Attempting to retrieve a result from an asynchronous function in Javascript has proven challenging.
After coming across the query: How do I return the response from an asynchronous call?, I endeavored to incorporate the callback solution, yet encountered issues.
The code snippet in question is as follows:
function getLocation(callback){
var lat;
var long;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude;
long = position.coords.longitude;
}, function()
{
console.log('Please enable geolocation in your browser.');
});
} else {
alert('It seems like geolocation is not enabled in your browser.');
}
var res = {
"lat": lat,
"long": long
};
callback(res);
}
function getEventNearYou(){
var list = [];
getLocation(function(obj){
var lat = obj.lat;
var long = obj.long;
$.ajax({
url : 'http://www.skiddle.com/api/v1/events/search/?api_key=myapikey' + '&latitude=' + lat + '&longitude=' + long + '&radius=800&eventcode=LIVE&order=distance&description=1',
type : "GET",
async : false,
success : function(response) {
$(response).find("results").each(function() {
var el = $(this);
var obj = {
"eventname" : el.find("eventname").text(),
"imageurl" : el.find("imageurl").text(),
}
list.push(obj);
});
}
});
return list;
});
}
Essentially, the goal is to determine the current location and send an HTTP GET request to www.skiddle.com for nearby events.
The execution of this function looks like this:
var x = getEventNearYou();
However, an error has occurred due to undefined values for lat
and long
.