JavaScript doesn't seem to wait for return values

后端 未结 4 1334
我寻月下人不归
我寻月下人不归 2020-12-29 20:28

I\'ve been struggling with this for a while now. I\'m new to Javascript, and have been under the impression that the code I\'ve been writing has been running asynchronously.

4条回答
  •  借酒劲吻你
    2020-12-29 21:05

    I...have been under the impression that the code I've been writing has been running asynchronously.

    Yes, it does. Your geocode function cannot return the results of the call to the Google API, because the function returns before the Google call completes. See note below:

    function geocode(geocoder) {
        //do geocoding here...
    
        var address = "3630 University Street, Montreal, QC, Canada";
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
               // +---------- This doesn't return anything from your
               // v           geocode function, it returns a value from the callback
               return results;
                }
             else {
                alert("Geocode was not successful for the following reason: " + status);
            }
       });
    }
    

    Instead, you must code your geocode function so that it accepts a callback which it will call when it has the results. E.g.:

    // Added a callback arg ---v
    function geocode(geocoder, callback) {
        //do geocoding here...
    
        var address = "3630 University Street, Montreal, QC, Canada";
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
               // v---------- Call the callback
               callback(results);
                }
             else {
                alert("Geocode was not successful for the following reason: " + status);
                callback(null); // <--- Call the callback with a flag value
                                // saying there was an error
            }
       });
    }
    

    Then, instead of using it like this:

    var results = geocode(someArgHere);
    if (results) {
        doSomething(results);
    }
    else {
        doSomethingElse();
    }
    

    You call it like this:

    geocode(someArgHere, function() {
        if (results) {
            doSomething(results);
        }
        else {
            doSomethingElse();
        }
    });
    

    E.g., you go fully asynchronous.

提交回复
热议问题