如何让 forEach 等待订阅完成?

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功能。

我尝试使用promiseand 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和运行中的代码。更改代码以在.PromisegetLocationsubscriberesolvegetLocation.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不是局部变量。鉴于它在每次迭代中都会被覆盖,这对我来说似乎有点无用。