当我逐步执行此代码时,这就是我观察到的行为:跳过响应处理程序代码,直到该函数的其余部分完成,然后执行该处理程序代码。这当然不是我想要的,因为响应后的代码取决于响应处理程序中的代码。

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

10-05 21:14
查看更多