Javascript 在javascript中等待回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11747440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wait for callback in javascript
提问by palvarez89
I'm trying to create a function that returns a object with information of a callback:
我正在尝试创建一个函数,该函数返回一个带有回调信息的对象:
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;
};
How can I do this? The function getLocation
return null value before successful
is executed.
我怎样才能做到这一点?函数getLocation
在successful
执行前返回空值。
Thanks!
谢谢!
回答by Rocket Hazmat
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.
因此,是getLocation
在触发回调之前返回。这就是异步方法的工作方式。
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.
你不能等待回调,这不是它的工作原理。您可以向 中添加回调getLocation
,该回调在完成后运行。
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:
现在var x = getLocation()
,您不再执行并期望返回值,而是这样称呼它:
getLocation(function(pos){
console.log(pos.longitude, pos.latitude);
});
回答by jbabey
I would recommend the approach in Rocket's answer. However, if you really wanted to, you could trigger the rest of your code when the getLocation
finishes by using a jQuery deferred object. This will give you more fine-grained control than just using the callbacks provided by getCurrentPosition
.
我会推荐火箭回答中的方法。但是,如果您真的愿意,您可以在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
});