Ali*_*tri 2 asynchronous subscribe promise async-await angular
我使用的是 Angular 6,我的数据库是 Firebase。现在我尝试根据其建筑物显示每个房间的名称。例如:
Building A
Room 1
Room 2
Building B
Room 1
Room 2
Run Code Online (Sandbox Code Playgroud)
但每次我尝试时,它都会先显示所有建筑物的名称,然后才会显示房间的名称。这就是我现在得到的:
Building A
Building B
Room 1
Room 2
Run Code Online (Sandbox Code Playgroud)
我发现发生这种情况是因为forEach
不断跳过该subscribe
功能。
我尝试使用promise
and await
,但它不起作用。也许是因为我使用方式不对?我不太确定如何以promise
正确的方式使用。
Building A
Room 1
Room 2
Building B
Room 1
Room 2
Run Code Online (Sandbox Code Playgroud)
我尝试使用setTimeout来延迟它,但它仍然不起作用。
Dav*_*ots 10
Array.forEach
仅适用于同步函数。将其更改为使用for...of
有效的语法。接下来是调用完成之前的代码resolve
和运行中的代码。更改代码以在.Promise
getLocation
subscribe
resolve
getLocation.subscribe
for(const building2 of buildings) {
console.log(building2.buildingName);
await new Promise ((resolve, reject) => {
this.navigationService.getLocation(this.user.orgId, this.completeBuildingId)
.subscribe(location => {
console.log('room' + location);
this.navMasterLocation = [];
resolve();
});
});
}
Run Code Online (Sandbox Code Playgroud)
请注意,它可以简化为:
for(const building2 of buildings) {
console.log(building2.buildingName);
const location = await this.navigationService.getLocation(this.user.orgId, this.completeBuildingId).toPromise();
console.log('room' + location);
this.navMasterLocation = [];
}
Run Code Online (Sandbox Code Playgroud)
另请注意,我不太确定为什么使用而this.completeBuildingId
不是局部变量。鉴于它在每次迭代中都会被覆盖,这对我来说似乎有点无用。
归档时间: |
|
查看次数: |
6246 次 |
最近记录: |