0

只是想知道是否有人可以帮助我了解 Javascript 原则。如果我想将函数作为参数传递,我猜这是非常核心的。我对 Javascript 知之甚少,但我承认它的微妙之处可能还不够。

因此,调用 codeAddress,然后到达我的第一个警报 (HERE2),代码传递回我的 showOnMap 函数,然后到达我的第二个警报 (HERE3)。为什么我的 HERE3 警报显示在我的 HERE2 警报之前?我能做些什么来告诉 Javascript 等待吗?

提前致谢

function showOnMap() {
    var inputStart = document.getElementById('CurrentHitch_StartDescription').value;
    var inputEnd = document.getElementById('CurrentHitch_EndDescription').value;
    codeAddress(inputStart, true); //HERE1*************
    codeAddress(inputEnd, false);
    var bounds2 = new google.maps.LatLngBounds(this.markerStart.getPosition());
    bounds2.extend(this.markerEnd.getPosition());
    map.fitBounds(bounds2);
    alert('showOnMap'); //HERE3*************
}

function codeAddress(address, isStart) {
    geocoder.geocode({ 'address': address }, function (results, status) {
        alert('codeAddress'); //HERE2*************
        if (status == google.maps.GeocoderStatus.OK) {
            if (isStart) {
                markerStart.setPosition(results[0].geometry.location);
            }
            else {
                markerEnd.setPosition(results[0].geometry.location);
            }
        } else {
            alert("Sorry, couldn't find your destination: " + status);
        }
    });
    return;
}
4

2 回答 2

2

这是因为geocode异步发生(非阻塞代码,意味着将来的某个时间,完成后我会告诉你)。可能可以告诉 Google 的 api 同步工作(作为阻塞代码),但您最好将取决于结果的代码放在geocode.

于 2012-05-11T00:01:38.323 回答
0

Welcome to the ajaxworld...
geocode是 google 提供的一个 ajax 服务。

您发送一个异步请求,您不等待它返回,继续执行代码,“第三个”警报触发,异步请求返回,您触发“第二个”警报。

想想这段代码:

alert('1');
setTimeout(function(){ 
    alert('2');
}, 1000); // fire the function after one second.
alert('3');

现场演示

输出顺序:

1,3,2

于 2012-05-11T00:01:04.667 回答