繁体   English   中英

等待 subscribe 在 while 循环内完成其工作(打字稿)

[英]Wait for subscribe to finish its job inside while loop (typescript)

我有一个 while 循环,在 while 循环中我有两个订阅。 我怎样才能等待他们完成继续使用 while 循环?

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: 1
WHILE: 2
WHILE: 3
4
5
6

但我想得到的输出是

WHILE: 1
1
2
3

在 while 循环中甚至不需要this.counter++ 如果没有在 while 内部,它只会无限运行

而不是循环,有一个递归函数。

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

    });
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM