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