地理编码未等待承诺
Promise not awaited on geocode
所以我有以下代码,我认为它是正确等待的,但是当我更深入地研究它时,我发现它的反应非常快(足够快,可以在 angular 模板中使用) .
this.dataService.getSomeData().subscribe(async (res) => {
this.historyList = res;
this.historyList.forEach(async (element) => {
console.log('before')
let address = await this.geocode(element);
console.log(address)
element.address = address
});
console.log('after');
我的地理编码承诺如下所示:
async geocode(item:Location):Promise<string> {
return await new Promise(async (resolve) => {
const geocoder = new google.maps.Geocoder();
const location = new google.maps.LatLng(item.latitude, item.longitude);
geocoder.geocode({ location: location }, async (results, status) => {
if (status === 'OK') {
resolve(results[0].formatted_address);
}
});
});
}
现在,多个“之前”日志和一个“之后”日志将在任何地址返回之前显示在控制台中。谁能看到我可能哪里出错了? VS Code 对地理编码方法的等待没有任何问题,所以我有点难过。
谢谢
当您执行 .forEach(async element=>
时,它永远不会等待回调,如果您想按顺序执行它们,您可以将其切换到 for-of
循环:
this.dataService.getSomeData().subscribe(async (res) => {
this.historyList = res;
for(const element of this.historyList) {
console.log('before')
let address = await this.geocode(element);
console.log(address)
element.address = address
}
console.log('after');
}
或者并行使用 Promise.all
:
this.dataService.getSomeData().subscribe(async (res) => {
this.historyList = res;
// use map to get a promise for each.
await Promise.all(this.historyList.map(async (element) => {
console.log('before')
let address = await this.geocode(element);
console.log(address)
element.address = address
}));
console.log('after');
}
所以我有以下代码,我认为它是正确等待的,但是当我更深入地研究它时,我发现它的反应非常快(足够快,可以在 angular 模板中使用) .
this.dataService.getSomeData().subscribe(async (res) => {
this.historyList = res;
this.historyList.forEach(async (element) => {
console.log('before')
let address = await this.geocode(element);
console.log(address)
element.address = address
});
console.log('after');
我的地理编码承诺如下所示:
async geocode(item:Location):Promise<string> {
return await new Promise(async (resolve) => {
const geocoder = new google.maps.Geocoder();
const location = new google.maps.LatLng(item.latitude, item.longitude);
geocoder.geocode({ location: location }, async (results, status) => {
if (status === 'OK') {
resolve(results[0].formatted_address);
}
});
});
}
现在,多个“之前”日志和一个“之后”日志将在任何地址返回之前显示在控制台中。谁能看到我可能哪里出错了? VS Code 对地理编码方法的等待没有任何问题,所以我有点难过。
谢谢
当您执行 .forEach(async element=>
时,它永远不会等待回调,如果您想按顺序执行它们,您可以将其切换到 for-of
循环:
this.dataService.getSomeData().subscribe(async (res) => {
this.historyList = res;
for(const element of this.historyList) {
console.log('before')
let address = await this.geocode(element);
console.log(address)
element.address = address
}
console.log('after');
}
或者并行使用 Promise.all
:
this.dataService.getSomeData().subscribe(async (res) => {
this.historyList = res;
// use map to get a promise for each.
await Promise.all(this.historyList.map(async (element) => {
console.log('before')
let address = await this.geocode(element);
console.log(address)
element.address = address
}));
console.log('after');
}