Returning value from function inside a function

Deadly 提交于 2019-12-11 03:40:00

问题


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.



来源:https://stackoverflow.com/questions/5596026/returning-value-from-function-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!