[英]Wait for callback in javascript
我正在尝试创建一个返回带有回调信息的对象的函数:
var geoloc;
var successful = function (position) {
geoloc = {
longitude: position.coords.longitude,
latitude: position.coords.latitude
};
};
var getLocation = function () {
navigator.geolocation.getCurrentPosition(successful, function () {
alert("fail");
});
return geoloc;
};
我怎样才能做到这一点? 函数getLocation
在执行successful
之前返回null值。
谢谢!
使用回调是因为该函数是异步的。 回调在未来的某个时刻运行。
所以,是的, getLocation
在触发回调之前返回。 这就是异步方法的工作原理。
你不能等待回调,这不是它的工作方式。 您可以向getLocation
添加一个回调,该回调在完成后运行。
var getLocation = function(callback){
navigator.geolocation.getCurrentPosition(function(pos){
succesfull(pos);
typeof callback === 'function' && callback(geoloc);
}, function(){
alert("fail");
});
};
现在不是做var x = getLocation()
并且期望返回值,而是像这样调用它:
getLocation(function(pos){
console.log(pos.longitude, pos.latitude);
});
我会在Rocket的答案中推荐这种方法。 但是,如果您真的想要,则可以在getLocation
使用jQuery延迟对象完成时触发其余代码。 与仅使用getCurrentPosition
提供的回调相比,这将为您提供更细粒度的控制。
// create a new deferred object
var deferred = $.Deferred();
var success = function (position) {
// resolve the deferred with your object as the data
deferred.resolve({
longitude: position.coords.longitude,
latitude: position.coords.latitude
});
};
var fail = function () {
// reject the deferred with an error message
deferred.reject('failed!');
};
var getLocation = function () {
navigator.geolocation.getCurrentPosition(success, fail);
return deferred.promise(); // return a promise
};
// then you would use it like this:
getLocation().then(
function (location) {
// success, location is the object you passed to resolve
},
function (errorMessage) {
// fail, errorMessage is the string you passed to reject
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.