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);
});

您不会用DeferredPromiseThenable来喂养$.when,因此它会立即触发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编码!

最新更新