Angular:Promise.all()的具体应用

现有项目开发中,从后台获取数据用异步promise,可是异步的数据要顺序获取真的是好费劲啊,还好解锁了promise.all(),下面来看代码吧!

遍历this.groupList通过groupID获取组内成员,将获取的成员push到finalAccount数组,this.groupList遍历完成以后,需要将finalAccount发送到父组件内,可是异步的话怎么发都有问题惹,改成promise.all()问题就解决了。

 const array = [];
    this.groupList.forEach(
      x => {
        if (x.checked) {
          const promise1 = this.customService.getCustomGroupUsers(x.id).then(res => {
            this.cs.log('promise1');
            for (const user of res.users) {
              this.finalAccount.push({
                groupId: x.id,
                groupName: x.name,
                openId: user.openId,
                userName: user.userName,
              })
            }
            return Promise.resolve(res.users);
          });
          array.push(promise1);
        }
      }
    );

    Promise.all(array)
    .then(() => {
      console.log('emit');
      this.cs.log('emit');
      this.onFinalAccount.emit(this.finalAccount);
      this.onCloseLink.emit(false);
    });

猜你喜欢

转载自www.cnblogs.com/xiaojing140421/p/9089187.html