等待javascript中的回调

时间:2012-07-31 19:20:47

标签: 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;
};

我该怎么做?函数getLocation在执行successful之前返回空值。

谢谢!

2 个答案:

答案 0 :(得分:25)

使用回调是因为该函数是异步的。回调将在未来的某个时刻运行。

因此,在触发回调之前返回yes 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);
});

答案 1 :(得分: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
    }); 
相关问题