简体   繁体   中英

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.

你应该放管后!

   .pipe(take(1)).toPromise

Just a few other options for those who want to be crazy:

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

or

const foo = (await this.afs.doc('docPath').get().toPromise()).data();

or

const foo = (await this.afs.doc('docPath').get().pipe(take(1)).toPromise()).data();

or

const foo =  (await this.afs.doc('docPath').snapshotChanges().pipe(take(1))
.toPromise()).payload.data();

But the shortest is:

const foo = (await this.afs.doc('docPath').ref.get()).data();

And anywhere you can use take(1) you can use first() if you want to emit an error.

For more Firebase promises, see here .

J

firstValueFrom and lastValueFrom is definitly a better alternative for many reasons:

  1. The naming is more readable and self explanatory.
  2. The additional ability to select either first or last value.
  3. The additional ability to declare a default value in case the observable didn't emit any

Reference: https://stackoverflow.com/a/69215890/5191209

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM