等待订阅在 while 循环中完成其工作(打字稿)

我有一个 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

this.counter++在 while 循环中甚至不需要。如果没有 while 本身,它就会无限运行


温温酱
浏览 140回答 1
1回答

不负相思意

使用递归函数代替循环。this.counter = 0;this.max = 3;function subscribe() {&nbsp;&nbsp;&nbsp; this.ms.getPopular(this.tv, this.counter).subscribe(val => {&nbsp; &nbsp; this.afstore.collection("matches").doc(this.id).valueChanges().pipe(take(1)).subscribe((val2: any) => {&nbsp; &nbsp; &nbsp; if (this.counter == this.max) {&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; this.counter++;&nbsp; &nbsp; &nbsp; &nbsp; this.subscribe();&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; });}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript