在forEach中返回一个promise

时间:2018-01-08 15:10:29

标签: angular typescript promise ionic3

您能否告诉我如何在promise方法下返回deleteBudgets()?因为我需要在await方法中使用updateBudgets()

deleteBudgets

  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

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

1 个答案:

答案 0 :(得分:4)

创建一个承诺数组:

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

然后使用promise.all等待所有承诺得到解决:

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

的文档