JavaScript doesn't seem to wait for return values

后端 未结 4 1313
我寻月下人不归
我寻月下人不归 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:18

    You seem to have a good understanding of the problem, but it sounds like you aren't familiar with the way to solve it. The most common way to address this is by using a callback. This is basically the async way to wait for a return value. Here's how you could use it in your case:

    function initialize() {
        //Geocode Address to obtin Lat and Long coordinates for the starting point of our map
        geocoder = new google.maps.Geocoder();
        geocode(geocoder, function(results) {
            // This function gets called by the geocode function on success
            makeMap(results[0].geometry.location.lat(), results[0].geometry.location.lng());        
        });
    }
    
    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) {
                // Call the callback function instead of returning
                callback(results);
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
       });
    
    }
    
    ...
    

提交回复
热议问题