函数返回undefined而console.log是期望值(javascript / nodejs)

时间:2017-10-30 21:47:22

标签: javascript function undefined return-value

这是Github的示例代码。我正在尝试对用户提交的地址进行地理编码,并通过创建函数geocodeAddress来提取更多信息(请参阅第二个块)。



// Geocode an address.
googleMapsClient.geocode({
  address: '1600 Amphitheatre Parkway, Mountain View, CA'
}, function(err, response) {
  if (!err) {
    console.log(response.json.results);
  }
});




当我在console.log中运行它所使用的对象但返回undefined。我试图在全局范围内初始化我的对象但没有成功。



exports.geocodeAddress = function (address) {
    var newGeocodedAddress = {};
    googleMapsClient.geocode({ address: address }, function(err, response) {
        if (!err) {
            newGeocodedAddress.lat_lng = [response.json.results[0].geometry.location.lat, response.json.results[0].geometry.location.lng];
            newGeocodedAddress.formatted_address = response.json.results[0].formatted_address;
            newGeocodedAddress.place_id = response.json.results[0].place_id;
            var address_components = response.json.results[0].address_components;
            for (var i = 0; i < address_components.length; i++){
                if ('locality' === address_components[i].types[0]) {
                    newGeocodedAddress.city_name = address_components[i].long_name;
                }
                if ('administrative_area_level_1' === address_components[i].types[0]) {
                    newGeocodedAddress.province = address_components[i].short_name;
                }
                if ('country' === address_components[i].types[0]) {
                    newGeocodedAddress.country_code = address_components[i].short_name;
                }
                if ('postal_code' === address_components[i].types[0]){
                    newGeocodedAddress.postal_code = address_components[i].long_name;
                }
            }
        }
        // console.log(newGeocodedAddress) returns the expected value
        return newGeocodedAddress; // returns undefined
    });
};
&#13;
&#13;
&#13;

强文

0 个答案:

没有答案