У меня есть небольшой фрагмент кода, который переводит местоположение 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);
});



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы не используете $.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.info('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!