等到所有的承诺都解决了/ Firestore

时间:2018-01-17 21:57:17

标签: angular typescript promise ionic3 google-cloud-firestore

你能告诉我们如何等待所有的承诺得到解决吗?此时它移动到下一行而不完成下面的操作。我需要完全完成foreach,然后转到下一行。那我该怎么做呢?

forEach(project.projectDetail.memberList, async (m) => {
        const memberDocumentRef: firebase.firestore.DocumentReference = this.fireStore.doc(`members/${m.id}`).ref;
        await this.fireStore.firestore.runTransaction(transaction => {
          return transaction.get(memberDocumentRef).then(memberDoc => {
            let currentProjects: Project[] = memberDoc.data().projects;
            const finalProjects = filter(currentProjects, (p: Project) => { return p.id != project.projectDetail.id; });//projects Without Updated Project
            finalProjects.push(project.projectDetail);
            transaction.update(memberDocumentRef, { projects: Object.assign({}, finalProjects) });//update projects on each member
          });
        });
      });

1 个答案:

答案 0 :(得分:3)

使用Promise.all,将forEach更改为map

// This promise.all returns a promise that will resolve when all the inner promises complete.
// You can either put dependent code in its .then method, or await it:

 await Promise.all(project.projectDetail.memberList.map(async (m: Member) => {
    const memberDocumentRef: firebase.firestore.DocumentReference = this.fireStore.doc(`members/${m.id}`).ref;
    await this.fireStore.firestore.runTransaction(transaction => {
      return transaction.get(memberDocumentRef).then(memberDoc => {
        let currentProjects: Project[] = memberDoc.data().projects;
        const finalProjects = filter(currentProjects, (p: Project) => { return p.id != project.projectDetail.id; });//projects Without Updated Project
        finalProjects.push(project.projectDetail);
        transaction.update(memberDocumentRef, { projects: Object.assign({}, finalProjects) });//update projects on each member
      });
    });
  }));