Returning value from function inside a function

2019-07-21 10:44发布

问题:

I'm using goMap and I'm trying to add a function inside it, but I cannot get it to return when the function is called. If I use alert() inside the function, it has the values I need it that should be returned.

getAddress: function(latlngcoords)
{
    var goMap = this;
    var input = latlngcoords;
    var latlngStr = input.split(",", 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    var address;

    geocoder.geocode({'latLng': latlng}, function(results, status) 
    {
        if(status == google.maps.GeocoderStatus.OK) 
        {
            if(results) 
            {   
                address = results;
                //alert(address); <-- works but
            }
        }
    });

    return address; // won't return at all?
},

It's called by doing: $.goMap.getAddress() but with a latitude and longitude in the argument. I need it to return the values by return address but it won't return anything at all.

How will I be able to get it to return the value?

回答1:

geocode is an asynchronous function. It starts when you call it, but that's all. (That's why it accepts a callback.) So your getAddress function is returning before address is set by the callback.

You need to have your getAddress function accept a callback as well, and return the result that way, e.g.

getAddress: function(latlngcoords, callback)
                                // ^--- callback parameter
{
    var goMap = this;
    var input = latlngcoords;
    var latlngStr = input.split(",", 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    var address;

    geocoder.geocode({'latLng': latlng}, function(results, status) 
    {
        if(status == google.maps.GeocoderStatus.OK) 
        {
            if(results) 
            {   
                address = results;
                callback(address);
            //  ^--- call it with the result
            }
        }
    });
},

Naturally this means that the code calling getAddress has to handle the fact that getAddress is also asynchronous.