Skip to content
Advertisement

.toPromise() and lastValueFrom() in rxjs

I have this observable

JavaScript

I call it with

JavaScript

.toPromise() is deprecated, so I would like to change the call with lastValueFrom():

JavaScript

but I receive the following error:

JavaScript

UPDATE: for now, resolved with:

JavaScript

but is there a better solution?

Advertisement

Answer

Is there a better solution?

Yes and no.

In your case mergeMap(_ => EMPTY) will ensure that your observable completes without emitting a value. Promises resolve to a value or they error. So the only thing to do here that meets the spec is to throw an error.

A work-around

You can sidestep this by emitting something. For example, here I emit null after the source completes:

JavaScript

Now your promise will resolve with a null once the observable completes successfully.

Something idiomatic

Rather than changing your code, you can change how you call it. This way you don’t need to worry about how Observables and Promises interact.

Instead of await lastValueFrom(createMyRecord()); write:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement