如何在 Array.prototype.map 中使用 await 来等待

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


防爆代码:


this.fooBarResponse.fooBars.map(async (x) => {

      x.fooBar = await this.fooBarService

        .getFooBar(x.fooBarId.toString())

        .toPromise();


      return x;

    });

foobar.service.ts


getFooBar(id: string): Observable<FooBar> {

    return this.fooBarsCollection.doc<FooBar>(id).valueChanges();

}


qq_遁去的一_1
浏览 92回答 2
2回答

慕勒3428872

Array#map是同步的。请改用for...of循环。for(const x of this.fooBarResponse.fooBars){&nbsp; &nbsp; x.fooBar = await this.fooBarService&nbsp; &nbsp; &nbsp; &nbsp; .getFooBar(x.fooBarId.toString())&nbsp; &nbsp; &nbsp; &nbsp; .pipe(take(1))&nbsp; &nbsp; &nbsp; &nbsp; .toPromise();}

温温酱

将您的 fooBars 数组减少为一个可观察到的 switchMap 从一个到下一个const { of } = rxjs;const { switchMap, delay } = rxjs.operators;const fooBarResponse = {&nbsp; fooBars: [{ fooBarId: 1 }, { fooBarId: 2 }, { fooBarId: 3 }, { fooBarId: 4 }, { fooBarId: 5 }, { fooBarId: 6 } ,{ fooBarId: 7 } , { fooBarId: 8 }]}const fooBarService = {&nbsp; getFooBar: x => of(`emitted ${x}`).pipe(delay(500))};fooBarResponse.fooBars.reduce(&nbsp; (obs$, x) => obs$.pipe(&nbsp; &nbsp; switchMap(_ => {&nbsp; &nbsp; &nbsp; console.log(`Switching from foobar ${x.fooBarId}`);&nbsp; &nbsp; &nbsp; return fooBarService.getFooBar(x.fooBarId.toString());&nbsp; &nbsp; })&nbsp; ),&nbsp; of(null) // start with some random observable).subscribe(finalEmit => {&nbsp; console.log(finalEmit);});<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.0/rxjs.umd.min.js"></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript