Sampath
Sampath

Reputation: 65870

Wait till all the promises are resolved / Firestore

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

Upvotes: 1

Views: 1022

Answers (1)

CRice
CRice

Reputation: 32176

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

Upvotes: 3

Related Questions