Robin
Robin

Reputation: 625

Typescript async/await with Observable Or Promise

Can i use the async with await like this? Am i killing the async/await here? The code below is working without error, I know that the async/await only works with Promise<T>. My getItem is an Observable. Thanks.

roleService.getItem({ page: p.pageIndex + 1, pageSize: p.pageSize })
.takeUntil(this.unsubscribe$)
.map((res: ResponseDto) => <DtoModel>res.contentBody)
.do(async (dto: DtoModel) => await this.subject.next(dto.content)) // working wihtout error
.subscribe(async (dto: DtoModel) => await (this.pager = dto.pager), //working without error
          (error: any) => Observable.throw(error));

Upvotes: 2

Views: 2652

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105499

You can use the async functions the way you do but it will have no effect in your example. You have to understand that async function returns a promise:

const fn = async function() {};
fn() instanceof Promise

So if you use it in the observable chain you will receive a promise:

interval(500)
  .first()
  .map(async (v) => {
    return v;
  })
  .subscribe((v) => {
    console.log(v instanceof Promise); // logs `true`
  });

The way you constructed your example it won't have any effect on the observables chain because output from do operator is ignored and there's no listener for the output from the subscribe callback. So basically there's no reason to use async there.

If you wanted instead to wait until async function resolves and get the results of that function use mergeMap operator:

interval(500)
  .first()
  .map(async (v) => {
    return v;
  })
  .mergeMap((p) => {
    return p;
  })
  .subscribe((v) => {
    console.log(v);
  });

Upvotes: 2

Related Questions