为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

温温酱 2023-03-24 16:00:03
我有一个 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: 1WHILE: 2WHILE: 3456但我想要得到的输出是WHILE: 1123this.counter++在 while 循环中甚至不需要。如果没有 while 本身,它就会无限运行
查看完整描述

1 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

使用递归函数代替循环。


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

      }


    });

  });

}


查看完整回答
反对 回复 2023-03-24
  • 1 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号