I have read that toPromise()
is being deprecated in RxJS 7 and will be removed in RxJS 8.
I have often used it with async await syntax in angular to handle http calls. Is it considered an anti pattern?
I understand the concept of streams but an http call only emit a single value. I don't get the point of observable for a simple http call. What should I use next? should I fully embrace reactive programming?
firstValueFrom
and lastValueFrom
is definitly a better alternative for many reasons:
await lastValueFrom(data$, {defaultValue: 'Some default value'})
For more about this checkout the video below:
https://www.youtube.com/watch?v=3aeK5SfWBSU
Why is this happening?
As mentioned here, these are the main reasons why toPromise
is being deprecated:
One goal was to remove it from the
Observable
prototype and turn it into a standalone util function.The naming of
toPromise
is not the best. Especially when used in combination withawait
it does not read very well:await categories$.toPromise()
vsawait lastValueFrom(categories$)
The type information of
toPromise
is wrong. When the sourceObservable
completed without ever emitting a single value - it resolved withundefined
. It should reject in that case. APromise
is a "promise" that when it resolves a value will be there - and be itundefined
. But when the stream completes without ever emitting a value you can't differentiate between a stream that a emittedundefined
on purpose and a stream that completed without ever emitting anymore
What should you use next?
If you really insist doing it the promise way, lastValueFrom
/firstValueFrom
. Otherwise switching to reactive programming would be the way to go.
This link should help-
https://indepth.dev/posts/1287/rxjs-heads-up-topromise-is-being-deprecated