本文介绍了等到所有的承诺都解决了/ Firestore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你能告诉我们如何等待所有的承诺得到解决吗?此时它移动到下一行而不完成下面的操作。我需要完全完成 foreach
,然后转到下一行。那我怎么能这样做?
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
});
});
});
推荐答案
使用 Promise.all
,并将 forEach
更改为地图
:
// 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
});
});
}));
这篇关于等到所有的承诺都解决了/ Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!