等到所有的承诺都解决了/公司的FireStore(Wait till all the promise

2019-09-29 23:32发布

你能告诉如何要等到所有的承诺都解决了? 此时它移动到下一行没有完成下面的操作。 我需要完全完成foreach ,之后移动到下一个line.So我该怎么办呢?

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

Answer 1:

使用Promise.all ,并更改forEachmap

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


文章来源: Wait till all the promises are resolved / Firestore