how to return value to parent function from nested anonymous function

戏子无情 提交于 2019-12-03 16:04:32

Since it's asynchronous, you should pass a callback which handles the function:

function codeAddress(address, callback) {
    (new google.maps.Geocoder()).geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback(String(results[0].geometry.location.Ya) + ','
                    + String(results[0].geometry.location.Za))
        } else {
            callback(status);
        }
    });
}

codeAddress("test", function(result) {
    // do stuff with result
});

If you're using jQuery, you could also use deferred:

function codeAddress(address, callback) {
    var dfd = new jQuery.Deferred();

    (new google.maps.Geocoder()).geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
             // trigger success
            dfd.resolve(String(results[0].geometry.location.Ya) + ','
                    + String(results[0].geometry.location.Za));
        } else {
            // trigger failure
            dfd.reject(status); 
        }
    });

    return dfd;
}

codeAddress("some address").then(
    // success
    function(result) {
        // do stuff with result
    },
    // failure
    function(statusCode) {
        // handle failure
    }
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!