簡體   English   中英

如何使forEach等待訂閱完成?

[英]How to make forEach wait for subscribe to finish?

我正在使用Angular 6,而我的數據庫是Firebase。 現在,我嘗試根據房間的建築物顯示每個房間的名稱。 例如:

Building A
Room 1
Room 2
Building B
Room 1
Room 2

但是每次嘗試時,它將首先顯示所有建築物名稱,然后才顯示房間的名稱。 這是我現在得到的:

Building A
Building B
Room 1
Room 2

我發現發生這種情況是因為forEach一直跳過subscribe功能。

我嘗試使用promiseawait ,但是它不起作用。 也許是因為我使用錯誤的方式? 我不太確定如何以正確的方式使用promise

async loadData(){
    this.navigationService.user
        .subscribe( user => {
        console.log(user);
        this.user = user;
        this.navigationService.getBuildings(this.user.orgId)
            .subscribe( building => {
            this.navMasterBuilding = [];
            this.buildings = building;
            this.buildings.forEach( async building2 => {
                this.completeBuildingId = building2.completeBuildingId;
                this.buildingName = building2.buildingName;
                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();
                });   
            });
        });
    });
}

我試圖通過使用setTimeout來延遲它,但是它仍然不起作用。

Array.forEach僅適用於同步功能。 將其更改為使用有效的for...of語法。 接下來,您可以在對getLocation的調用已完成並且subscribe的代碼已運行之前resolve Promise 更改代碼以在getLocation.subscribe調用resolve

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();
             });                    
    });   
}

請注意,它可以簡化為:

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 = [];             
}

還要注意,我不太確定為什么要使用this.completeBuildingId而不是局部變量。 鑒於它在每次迭代中都會被覆蓋,這對我來說似乎沒有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM