Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I use instead of toPromise() when using await on an Observable?

This page says "toPromise has been deprecated! (RxJS 5.5+)" but I've been using it lately with AngularFire2 (when I only want one result) like this:

const foo = await this.afs.doc(`docPath`).valueChanges().toPromise();

Should I not be doing this? If not, what is the await alternative?

UPDATE:

After the answer below I've changed this:

const foo = await this.afs.doc(`docPath`).valueChanges().toPromise();

...to this:

const foo = await (new Promise(resolve => this.afs.doc(`docPath`).valueChanges().pipe(first()).subscribe(result => resolve(result))));

Could someone please explain to me how this is an improvement?! Seems like a step backward to me.

like image 667
Jus10 Avatar asked Aug 03 '18 17:08

Jus10


People also ask

Why is toPromise 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 I use await on Observable?

You can use Observables with Promises and with async/await to benefit from the strengths of each of those tools.

What is toPromise () in angular?

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!

How do you wait for an Observable to finish?

The concatMap() operator runs each observable in sequence and waits for the previous observable to complete before continuing to the next one, if a Promise is returned in concatMap() then it will wait for the promise to resolve before completing the observable.


1 Answers

You just should put after pipe!

   .pipe(take(1)).toPromise
like image 93
Adrian Lemes Caetano Avatar answered Oct 18 '22 19:10

Adrian Lemes Caetano