问题
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