Функция jQuery $ .when () не работает - PullRequest
0 голосов
/ 02 мая 2018

У меня есть небольшой кусочек кода, который переводит локацию 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 голосов
/ 02 мая 2018

Вы не кормите $.when Deferred, или Promise, или 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!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...