溫溫醬
2023-03-24 16:00:03
我有一個(gè) while 循環(huán),在 while 循環(huán)內(nèi)我有兩個(gè)訂閱。我怎樣才能等他們完成才能繼續(xù)使用 while 循環(huán)?this.counter = 1;array[0] = 3;while(this.counter <= array[0]) { console.log("WHILE: "+this.counter); this.ms.getPopular(this.tv, this.counter).subscribe(val => { this.afstore.collection("matches").doc(this.id).valueChanges().pipe(take(1)).subscribe((val2: any) => { console.log(this.counter); if(this.counter == array[0]) { return; } //console.log("YES"); this.counter++; }); }); this.counter++; }我目前的輸出是WHILE: 1WHILE: 2WHILE: 3456但我想要得到的輸出是WHILE: 1123this.counter++在 while 循環(huán)中甚至不需要。如果沒有 while 本身,它就會(huì)無(wú)限運(yùn)行
1 回答

不負(fù)相思意
TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
使用遞歸函數(shù)代替循環(huán)。
this.counter = 0;
this.max = 3;
function subscribe() {
this.ms.getPopular(this.tv, this.counter).subscribe(val => {
this.afstore.collection("matches").doc(this.id).valueChanges().pipe(take(1)).subscribe((val2: any) => {
if (this.counter == this.max) {
return;
} else {
this.counter++;
this.subscribe();
}
});
});
}
添加回答
舉報(bào)
0/150
提交
取消