角打字稿等待方法完成不起作用

时间:2020-02-28 08:50:04

标签: angular typescript async-await

我正在修改angular8打字稿类。我想等待方法完成再实施进一步的逻辑。请在下面找到我的代码:

  aync processData() {
    await test();
    console.log('-- after async call --);
  }

  async test() {
    if (this.data && this.data.itemData) {
      this.data.itemData.map(async (itemData) => {
        await this.itemCrudService.getItemDataById(itemData.itemId)
        .subscribe((response) => {
          console.log('response', response);
        })
      })
    }
  }

在这里,我要等待test()方法来准备要在processData()方法中进一步使用的项目数据(某些全局数组)。

请注意,它还涉及通过itemId检索商品数据的http调用。

但是测试方法调用之后的console.log在测试方法完成之前被调用。

1 个答案:

答案 0 :(得分:0)

您不能像这样通过管道进行异步,因为存在嵌套的异步调用。因此,您正在等待通话完成,而不是等待执行结束。

首先:在这种情况下,您不应使用全局变量,因为当您忘记事物的顺序时,您会在途中询问许多错误。

相反,您应该使用适当的RxJs运算符正确表达您的语义。在这里,我想您想要类似的东西:

const dataPipes = ....map(itemData => this.itemCrudService.get...());
// Now, you create a new observable with all results:
const allValues = forkJoin(dataPipes);
// Now, you process all values when they arrive:
allValues.pipe(take(1)).subscribe(dataArray => { ...here you have all data... });

pipe(take(1))是为了避免退订,因为您只是等待响应。如果您更愿意Promise,也可以执行以下操作:

allValues.toPromise().then(dataArray => { ...here you have all data... });

您可以在official docs中获得有关所有可能的运算符和用法的更多信息,并在learnrxjs上获得示例。

相关问题