首页 > 解决方案 > jQuery $.when() 函数不起作用

问题描述

我有一小段代码,它将经纬度位置转换为人类可读的地址。我希望在显示人类可读地址之前先进行翻译。这就是为什么我想先使用 $.when() 来完成翻译。

但是,在运行时,不会显示人类可读的地址,仅显示默认值 'xxx'。也没有检测到错误。

var geocoder = new google.maps.Geocoder;

var lat1 = 39.983313,
  lon1 = -0.031963;

var addressLatLng = {
  lat: parseFloat(lat1),
  lng: parseFloat(lon1)
};

var addressHumanReadable = 'xxx';

$.when(
  geocoder.geocode({
    'location': addressLatLng
  }, function(results, status) {
    if (status === 'OK') {
      if (results[0]) {
        addressHumanReadable = results[0].formatted_address;

      } else {
        window.alert('No results found');
      }
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  })
).done(function(x) {
  alert(addressHumanReadable);
});

标签: javascriptjquerygoogle-maps-api-3

解决方案


您不$.when使用 aDeferred或 aPromise或 a来喂它Thenable,所以它会done立即触发(更多信息在这里https://api.jquery.com/jquery.when/

所以这是你的代码......稍微改变了一点,以便它可以执行你的黑暗魔法。

// With the power of Google Maps...
var geocoder = new google.maps.Geocoder;

// .. and some magic numbers!
var lat1 = 39.983313;
var lon1 = -0.031963;

// We shall translate them...
var addressLatLng = {
  lat: parseFloat(lat1),
  lng: parseFloat(lon1)
};

// ... to something that a Human can process!
var addressHumanReadable = 'xxx';

$.when(
    // We execute an anomymous function
    // that help us keep things clean
    (function(){
        // We need a deferred to indicate when we are ready
        var isDone = $.Deferred();

        // Run your async function
        geocoder.geocode(
            {'location': addressLatLng},
            function(results, status) {
                if (status === 'OK') {
                    if (results[0]) {
                        addressHumanReadable = results[0].formatted_address;
                    }
                    else {
                        window.alert('No results found');
                    }
                }
                else {
                    window.alert('Geocoder failed due to: ' + status);
                }

                // Set deferred as resolved
                isDone.resolve();
            }
        );

        // Return a jquery deferred
        return isDone;
    })()
).done(function() {
    // MAGIC!
    alert(addressHumanReadable);
});

但是等等还有更多!我不喜欢全局变量...我也不喜欢警报中断我的代码流...所以...我们可以删除addressHumanReadable地理编码中的警报。

// With the power of Google Maps...
var geocoder = new google.maps.Geocoder;

// .. and some magic numbers!
var lat1 = 39.983313;
var lon1 = -23452.031963;

// We shall translate them...
var addressLatLng = {
    lat: parseFloat(lat1),
    lng: parseFloat(lon1)
};

$.when(
    // We execute an anomymous function
    // that help us keep things clean
    (function(){
        // We need a deferred to indicate when we are ready
        var isDone = $.Deferred();

        // Run your async function
        geocoder.geocode(
            {'location': addressLatLng},
            function(results, status) {
                // Check for errors
                if (status !== 'OK') {
                    console.log('Oups... error : ' + status);
                    isDone.resolve(false);
                    return;
                }

                // Check if failed to resolve
                if (!results[0]) {
                    isDone.resolve(false);
                    return;
                }

                // No errors... so...
                isDone.resolve(results[0].formatted_address);
            }
        );

        // Return a jquery deferred
        return isDone;
    })()
).done(function(result) {
    if (result) {
        alert(result);
    }
    else {
        alert('Address not found!');
    }
});

快乐的 JavaScript 编码!


推荐阅读