首页 > 解决方案 > 如何在 Array.prototype.map 中使用 await 来等待 RxJS Observables

问题描述

如何在 getFooBar 返回 observable 的 map 函数中等待结果?

防爆代码:

this.fooBarResponse.fooBars.map(async (x) => {
      x.fooBar = await this.fooBarService
        .getFooBar(x.fooBarId.toString())
        .toPromise();

      return x;
    });

foob​​ar.service.ts

getFooBar(id: string): Observable<FooBar> {
    return this.fooBarsCollection.doc<FooBar>(id).valueChanges();
}

标签: javascriptangulardictionaryrxjsobservable

解决方案


Array#map是同步的。请改用for...of循环。

for(const x of this.fooBarResponse.fooBars){
    x.fooBar = await this.fooBarService
        .getFooBar(x.fooBarId.toString())
        .pipe(take(1))
        .toPromise();
}

推荐阅读