pal*_*z89 20 javascript asynchronous callback wait
我正在尝试创建一个返回带有回调信息的对象的函数:
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;
};
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?该函数getLocation在successful执行之前返回null值.
谢谢!
Roc*_*mat 25
使用回调是因为该函数是异步的.回调在未来的某个时刻运行.
因此,yes getLocation在触发回调之前返回.这就是异步方法的工作原理.
你不能等待回调,这不是它的工作方式.您可以添加一个回调函数getLocation,该函数在完成后运行.
var getLocation = function(callback){
navigator.geolocation.getCurrentPosition(function(pos){
succesfull(pos);
typeof callback === 'function' && callback(geoloc);
}, function(){
alert("fail");
});
};
Run Code Online (Sandbox Code Playgroud)
现在不是做var x = getLocation()和期望返回值,而是这样称呼它:
getLocation(function(pos){
console.log(pos.longitude, pos.latitude);
});
Run Code Online (Sandbox Code Playgroud)
jba*_*bey 20
我会在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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42830 次 |
| 最近记录: |