【问题标题】:Wait till all the promises are resolved / Firestore等到所有的承诺都解决了/Firestore
【发布时间】:2018-06-26 21:34:21
【问题描述】:

你能告诉我如何等到所有的承诺都解决了吗?此时它移动到下一行而不完成以下操作。我需要完全完成foreach,然后移至下一行。那么我该怎么做呢?

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

【问题讨论】:

    标签: angular typescript promise ionic3 google-cloud-firestore


    【解决方案1】:

    使用Promise.all,并将forEach 更改为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
          });
        });
      }));
    

    【讨论】:

    • 嘿,我注意到您编辑了答案。看起来仍然正确,但我想指出,如果您返回 this.fireStore... 承诺而不是等待它,一切仍然有效,但您不必将 map 函数声明为异步(除非您更喜欢这种方式)。跨度>
    • 非常感谢。上面的代码对我来说工作得很好:)
    猜你喜欢
    • 2015-10-19
    • 2014-03-12
    • 2016-01-10
    • 2017-05-25
    • 2022-01-17
    • 2017-12-12
    • 2020-10-22
    • 2017-06-13
    相关资源
    最近更新 更多