Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be using toPromise in rxjs6? What does it do?

I'm having a little trouble reading the rxjs documentation.

As far as I can see, this is the official documentation: https://rxjs-dev.firebaseapp.com/api

In the Observable documenation page under methods it has listed lift() and subscribe(), though later down the page, under examples, there are forEach(), pipe(), and toPromise().

None of those have usage notes - just argument specifiers.

Looking at this page: https://www.learnrxjs.io/operators/utility/topromise.html

We're told:

:warning: toPromise has been deprecated! (RxJS 5.5+)

How I am I meant to be reading this? toPromise was deprecated in 5.5x and continues to be deprecated?

like image 812
dwjohnston Avatar asked Aug 27 '18 05:08

dwjohnston


People also ask

What is the use of toPromise?

The toPromise function lives on the prototype of Observable and is a util method that is used to convert an Observable into a Promise . Inside this function we subscribe to the Observable and resolve the Promise with the last emitted value - attention - when the Observable completes!

Why toPromise is deprecated?

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 with await it does not read very well: await categories$.

Can we convert RxJS Observable into a Promise?

RxJS allows to turn any Observable into a Promise with the firstValueFrom function (note: since RxJS 7, toPromise is deprecated): const obs = of(1); const promise = firstValueFrom(obs);

What is Lastvaluefrom?

lastValueFromlinkConverts an observable to a promise by subscribing to the observable, waiting for it to complete, and resolving the returned promise with the last value from the observed stream.


1 Answers

TLDR; I think the documentation is incorrect.

toPromise is not deprecated.

Apparently there was some issue when toPromise was moved to operators and then removed in 5.5 beta.

toPromise was only available in rxjs/operators during a beta of 5.5. It was removed because it doesn't make any sense, it's not an operator, it's a method of subscription that results in a promise. See GH issue

Also there is no deprecation notice in the sources and none in the migration guide. Rxjs team is pretty reliable about deprecation warnings.

I think the documentation at https://www.learnrxjs.io/operators/utility/topromise.html is either wrong or it's referring to toPromise as operator - which has been removed.

like image 130
m1ch4ls Avatar answered Sep 19 '22 13:09

m1ch4ls