Wait till all the promises are resolved / Firestore

天涯浪子 提交于 2019-12-11 04:27:20

问题


Could you tell how to wait till all the promises are resolved? At this moment it moves to next line without completing below operation. I need to fully complete the foreach and after that move to the next line.So how can I do it?

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:


Use Promise.all, and change the forEach to a 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
      });
    });
  }));


来源:https://stackoverflow.com/questions/48310677/wait-till-all-the-promises-are-resolved-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!