为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_遁去的一_1 2022-11-11 14:58:23
如何在 getFooBar 返回 observable 的 map 函数中等待结果?防爆代码:this.fooBarResponse.fooBars.map(async (x) => {      x.fooBar = await this.fooBarService        .getFooBar(x.fooBarId.toString())        .toPromise();      return x;    });foobar.service.tsgetFooBar(id: string): Observable<FooBar> {    return this.fooBarsCollection.doc<FooBar>(id).valueChanges();}
查看完整描述

2 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

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


for(const x of this.fooBarResponse.fooBars){

    x.fooBar = await this.fooBarService

        .getFooBar(x.fooBarId.toString())

        .pipe(take(1))

        .toPromise();

}


查看完整回答
反对 回复 2022-11-11
?
温温酱

TA贡献1752条经验 获得超4个赞

将您的 fooBars 数组减少为一个可观察到的 switchMap 从一个到下一个


const { of } = rxjs;

const { switchMap, delay } = rxjs.operators;


const fooBarResponse = {

  fooBars: [{ fooBarId: 1 }, { fooBarId: 2 }, { fooBarId: 3 }, { fooBarId: 4 }, { fooBarId: 5 }, { fooBarId: 6 } ,{ fooBarId: 7 } , { fooBarId: 8 }]

}


const fooBarService = {

  getFooBar: x => of(`emitted ${x}`).pipe(delay(500))

};


fooBarResponse.fooBars.reduce(

  (obs$, x) => obs$.pipe(

    switchMap(_ => {

      console.log(`Switching from foobar ${x.fooBarId}`);

      return fooBarService.getFooBar(x.fooBarId.toString());

    })

  ),

  of(null) // start with some random observable

).subscribe(finalEmit => {

  console.log(finalEmit);

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.0/rxjs.umd.min.js"></script>


查看完整回答
反对 回复 2022-11-11
  • 2 回答
  • 0 关注
  • 76 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信