怎么来功能不等待另一个功能

edd*_*ddy 0 html javascript google-maps function

我有2个函数,函数A调用函数B,它对地址进行地理编码并将LatLng对象返回给函数A,但不知何故,函数A不等待函数B从Google返回结果.

function A() {
    var address = document.getElementById("txtbox").value;
    //geocoding here
    var here = B(address);
    if (here == null) {
        console.log("seems like geocode didn't work, defaulting value");
Run Code Online (Sandbox Code Playgroud)

在功能B中

function B(address) {
    var here;
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        console.log("geocoding");                                               
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results[0].geometry.location);
            currentlatlng = results[0].geometry.location;
            lng = currentlatlng.lng();
            lat = currentlatlng.lat();
            here = new google.maps.LatLng(lat, lng);
        } else {
            console.log("Geocode was not successful for the following reason: " + status);
        }
    });

    return here;
}
Run Code Online (Sandbox Code Playgroud)

但似乎控制台的输出是

seems like geocode didn't work, defaulting value
geocoding
Run Code Online (Sandbox Code Playgroud)

因此,似乎函数A调用函数B然后继续它.

我认为它会等待,但是根据我对谷歌地图api如何工作的理解,它本身并不"等待",所以我该怎么办?

jfr*_*d00 6

您的地理编码功能是异步的.它不等待.它的结果来自Ajax调用("Ajax"中的"A"代表异步).

您无法以同步方式使用异步函数进行编程.相反,您必须使用异步技术.在这种情况下,您获取地理编码信息后要运行的任何代码必须在地理编码操作的完成处理程序中执行或调用.你以后不能执行它B().你必须在里面的完成处理程序中执行它B().

如果您希望能够B()用于多种用途,那么您可以将回调传递到B()并调用在地理编码数据可用时调用的回调.

function A(){
    var address = document.getElementById("txtbox").value;
   //geocoding here
    B(address, function(geocodeData) {
        // use geocode data here
    });
}

function B(address, callback){
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
         console.log("geocoding");                                              
         if (status == google.maps.GeocoderStatus.OK) {
             console.log(results[0].geometry.location);
             var currentlatlng = results[0].geometry.location;
             var lng = currentlatlng.lng();
             var lat = currentlatlng.lat();
             var here = new google.maps.LatLng(lat, lng);
             // call your callback here and pass it the data
             callback(here);
         }else {
             console.log("Geocode was not successful for the following reason: " + status);
             }
        });
}
Run Code Online (Sandbox Code Playgroud)

仅供参考,你的变量应该被声明为局部变量(var在它们前面),这在异步函数中更为重要.