Javascript 在回调函数中访问数据
我有一个对地址进行地理编码的函数,它返回同一地址的城市名称Javascript 在回调函数中访问数据,javascript,angular,google-maps,typescript,google-geocoder,Javascript,Angular,Google Maps,Typescript,Google Geocoder,我有一个对地址进行地理编码的函数,它返回同一地址的城市名称 // geocode the given address geocodeAddress(address, callback) { this.mapsAPILoader.load().then(() => { var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function
// geocode the given address
geocodeAddress(address, callback) {
this.mapsAPILoader.load().then(() => {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
results[0].address_components.forEach(arrAddress => {
if (arrAddress.types[0] == "locality") {
callback(arrAddress.long_name);
}
})
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
});
};
当我调用该函数并想要打印城市名称时,它会从geocodeAddress函数下面的代码行打印“未定义”,然后正确打印城市名称
this.geocodeAddress(this.offerAddress, data => {
this.hostCity = data;
console.log(this.hostCity);
});
console.log(this.hostCity);
我试图在second console.log函数之前添加一些超时,但没有成功
所以,我对从geocoder返回数据后如何访问该值感兴趣,因为我需要使用该数据存储在数据库中,如果我尝试这样存储的话
this.geocodeAddress(this.offerAddress, data => {
this.hostCity = data;
this.service.addData({"address": this.offerAddress, "city": this.hostCity}, "/data")
.subscribe(data => {
this.router.navigate(['list']);
})
});
它存储数据,但路由器。导航无法正常工作
所以我需要一个解决方案来访问geocodeAddress回调函数之外的hostCity,或者如何正确调用这个geocodeAddress回调函数中的另一个函数如果您使用的是TypeScript,您可以让您的
geocodeAddress
方法返回一个Promise
,而不是使用回调,然后使用async/await
:
async geocodeAddress(address): Promise<string[]> {
return new Promise((resolve, reject) => {
this.mapsAPILoader.load().then(() => {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
const result: string[] = [];
results[0].address_components.forEach(arrAddress => {
if (arrAddress.types[0] == "locality") {
result.push(arrAddress.long_name);
}
});
resolve(results);
} else {
console.log("Geocode was not successful for the following reason: " + status);
reject(status);
}
});
});
});
};
通过这种方式,您可以获得异步编程的好处,同时还可以获得同步编程的简单性。您所说的“router.navigate无法正常工作”是什么意思?它将url导航到列表,但模板视图不是列表模板,它仍然在添加表单模板。我尝试调用另一个函数来打开错误对话框“this..confirmDialog(ErrorDialog,“Something error”);”。它会打开对话框,但没有消息,如果我在geocodeAddress回调函数之外调用此函数,那么除了处理
geocodeAddress
回调函数内的数据外,所有功能都会正常工作,请更改函数(结果,状态){…}
以获得(结果,状态)=>{…}
使用箭头函数保留此
的值。为什么回答此问题而不是将OP指向cannonical异步参考问题?OP是否使用typescript并不重要。重要的是OP不太了解异步编程是如何工作的。这个解决方案帮助了我。非常感谢。
const data: string[] = await this.geocodeAddress(this.offerAddress);
this.hostCity = data[0];
// do whatever you want now