当我遍历这段代码时,我观察到的行为是:跳过响应处理程序代码,直到函数的其余部分完成,然后执行处理程序代码。这当然不是我想要的,因为响应之后的代码取决于响应处理程序中的代码。
var geocoder = new google.maps.Geocoder();
function initializePlaces() {
var destination_LatLng;
var destination = document.getElementById("destination_address").value;
geocoder.geocode( {'address': destination}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
destination_LatLng = results[0].geometry.location;
} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
alert("Bad destination address.");
} else {
alert("Error calling Google Geocode API.");
}
});
// more stuff down here
}
导致这种行为的原因是什么?我如何更改代码以确保回调在其下面的代码之前运行?
Geocode异步运行,因此您必须将该代码放入回调中,或者制作另一个回调函数:
geocoder.geocode( {'address': destination}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
destination_LatLng = results[0].geometry.location;
} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
alert("Bad destination address.");
} else {
alert("Error calling Google Geocode API.");
}
//put more stuff here instead
});
或
function moreStuff(){
//more stuff here
}
geocoder.geocode( {'address': destination}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
destination_LatLng = results[0].geometry.location;
} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
alert("Bad destination address.");
} else {
alert("Error calling Google Geocode API.");
}
moreStuff();
});