输入&#39;预算[]&#39;不能分配类型&#39;承诺<预算[]>&#39;物业&#39;然后&#39;类型&#39;预算[]&#39;

时间:2018-01-27 05:36:24

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

我需要返回Promise<Budget[]>。但它显示错误:

  

[ts]类型&#39;预算[]&#39;不能分配类型&#39;承诺&#39;。
  物业&#39;然后&#39;类型&#39;预算[]&#39;中缺少。让预算:预算[]

你能告诉我如何从下面的方法中返回Promise<Budget[]>吗?

 createBudgets(data: Budget[], projectId: string): Promise<Budget[]> {
    let budgets: Budget[] = [];
    forEach(data, async (d) => {
      const budgetId: string = this.fireStore.createId();
      d.id = budgetId;
      budgets.push(d);
      await 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;// error shows here?
  }

1 个答案:

答案 0 :(得分:1)

如果要等待所有set方法调用完成执行,则需要将它们添加到数组中,并使用Promise.all等待它们完成:

async createBudgets(data: Budget[], projectId: string): Promise<Budget[]> {
    let budgets : Budget[] = [];
    await Promise.all(data.map(async (d) => {
        const budgetId: string = this.fireStore.createId();
        d.id = budgetId;
        budgets.push(d);
        await 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;
}