异步地理定位API和jQuery延迟对象

Asynchronous Geolocation API and jQuery Deferred Objects

本文关键字:jQuery 延迟 对象 API 定位 异步      更新时间:2023-09-26

我正在尝试使用Javascript Geolocation API来获取用户的经度和纬度。我希望能够通过调用getCoords()函数来获得这些信息,但遇到了问题。此代码:

function getCoords() {
    var coords = 5;
    var deferred = $.Deferred();
    getPosition = function() {
        navigator.geolocation.getCurrentPosition(
            function(position){
                deferred.resolve({
                    longitude: position.coords.longitude,
                    latitude: position.coords.latitude,
                });
            }, function(error) {
                deferred.reject();
            });
        return deferred.promise();
    }
    $.when(getPosition())
        .done( function(data) { 
            coords = data;
            console.log(coords); // Statement A
        });
    console.log(coords) //Statement B 
    return coords;
}
console.log(getCoords().toString()); //Statement C  

将以下内容输出到控制台

5  //Statement B
5  //Statement C
Object {longitude: 41.40338, latitude: 2.17403}  //Statement A

这是有意义的,因为地理定位API是异步的。如果我将代码的后半部分更改为:

$.when(getPosition())
    .done( function(data) { 
        coords = data;
        return coords;
    });
}

我收到以下错误消息:

Uncaught TypeError: Cannot call method 'toString' of undefined
    (anonymous function)

我在网上找到的所有其他例子都有$.when部分代码输出到alert而不是return方法。有人想过如何让getCoords()返回正确的对象吗?谢谢

您仍然会遇到您试图通过使用deferred解决的问题。您刚刚将返回延迟的函数封装在另一个试图同步返回异步结果的函数中。getCoords必须返回一个deferred,调用者必须知道并处理promise对象。

我会这样写:

function getCoords() {
    var coords = 5;
    var deferred = $.Deferred();
    navigator.geolocation.getCurrentPosition(function (position) {
        deferred.resolve({
            longitude: position.coords.longitude,
            latitude: position.coords.latitude,
        });
    }, function (error) {
        deferred.reject();
    });
    return deferred.promise();
}
//elsewhere
getCoords().done(function (data) {
    console.log(data);
}).fail(function () {
    console.log('failed');
});