我很难理解为什么我无法访问在我的函数中创建和返回的属性。如果我控制台记录对象本身。但是,如果我控制台log object.prop我得到了未定义。这是我的代码
function geocodeAddress(value) {
let geocoder = new google.maps.Geocoder(); // eslint-disable-line
let data = {};
geocoder.geocode({'address': value}, function(results, status) {
if (status === 'OK') {
data.longitude = results[0].geometry.location.lng();
data.latitude = results[0].geometry.location.lat();
}
});
return data;
}
const place = geocodeAddress('Leeds');
console.log(place.longitude,place.latitude);
答案 0 :(得分:0)
data
的属性在geocoder.geocode
函数中设置,即async
函数
这就是为什么它总是return {}
您有几种方法可以处理aysnc工作,其中一种方法是使用Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
function geocodeAddress(value) {
return new Promise(function(resolve, reject) {
let geocoder = new google.maps.Geocoder(); // eslint-disable-line
let data = {};
geocoder.geocode({
'address': value
}, function(results, status) {
if (status === 'OK') {
data.longitude = results[0].geometry.location.lng();
data.latitude = results[0].geometry.location.lat();
resolve(data)
} else {
reject(status);
}
});
})
}
let place = {};
geocodeAddress('Leeds').then(function(response) {
place = response
console.log(place.longitude, place.latitude);
}, function(error) {
console.log(error);
})
=>另一种选择是使用async/await
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function