Callbacks are used because the function is asynchronous. The callback runs at some point in the future.
So, yes getLocation
returns before the callback is triggered. That's how asynchronous methods work.
You cannot wait for the callback, that's not how it works. You can add a callback to getLocation
, that runs once it's done.
var getLocation = function(callback){
navigator.geolocation.getCurrentPosition(function(pos){
succesfull(pos);
typeof callback === 'function' && callback(geoloc);
}, function(){
alert("fail");
});
};
Now instead of doing var x = getLocation()
and expecting a return value, you call it like this:
getLocation(function(pos){
console.log(pos.longitude, pos.latitude);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…