jQuery $ .when()函数不起作用

时间:2018-05-02 14:08:26

标签: javascript jquery google-maps-api-3

我有一小段代码,它将Lat-Long位置转换为人类可读的地址。我想在显示人类可读的地址之前先进行翻译。这就是为什么我想先使用$ .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);
});

1 个答案:

答案 0 :(得分:1)

您不能使用$.whenDeferredPromiseThenable提供内容,因此会立即触发done(更多) info 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编码!