【问题标题】:Return a promise inside the forEach在 forEach 中返回一个承诺
【发布时间】:2018-06-17 14:11:12
【问题描述】:

你能告诉我如何在下面的deleteBudgets() 方法上返回promise 吗?因为我需要在updateBudgets()方法中使用await

删除预算

  deleteBudgets(data: Budget[], projectId: string): Promise<void> {
    forEach(data, (d: Budget) => {
      this.fireStore.doc(`projects/${projectId}/budgets/${d.id}`).delete();//here it returns Promise<void>
    });
  }

更新预算

 updateBudgets(data: Budget[], projectId: string): Budget[] {
    await this.deleteBudgets();//here  

    let budgets: Budget[] = [];
    forEach(data, (d) => {
      const budgetId: string = this.fireStore.createId();
      d.id = budgetId;
      budgets.push(d);
      this.fireStore.doc<Budget>(`projects/${projectId}/budgets/${budgetId}`).set({
        id: budgetId,
        amount: d.amount,
        contingency: d.contingency,
        budgetGroup: d.budgetGroup,
        creationTime: moment().format()
      })
    })
    return budgets;
  }

【问题讨论】:

  • 使用data.map()Promis.all 得到deleteBudgets的结果
  • 为什么需要使用await?您可以使用回调并在回调函数中实现剩余的代码块。
  • 如果你能把它放在一个解决方案中,那就太好了。然后我可以测试它。现在我还不清楚。 @ponury-kostek

标签: angular typescript promise ionic3


【解决方案1】:

创建一个promise数组:

deleteBudgets(data: Budget[], projectId: string): Promise<void> {
  data.map((d: Budget) => this.fireStore.doc(`projects/${projectId}/budgets/${d.id}`).delete());
}

然后使用promise.all等待所有的promise被解析:

deleteBudgets(data: Budget[], projectId: string): Promise<void[]> {
  return Promise.all(data.map((d: Budget) => this.fireStore.doc(`projects/${projectId}/budgets/${d.id}`).delete()));
}

promise.all 的文档

【讨论】:

  • 美丽。非常感谢:)
猜你喜欢
  • 2015-11-27
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 2016-07-20
相关资源
最近更新 更多