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.
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.
Share Improve this question edited Aug 3, 2018 at 20:34 Jus10 asked Aug 3, 2018 at 17:20 Jus10Jus10 15.7k22 gold badges58 silver badges80 bronze badges 4 |3 Answers
Reset to default 16You just should put after pipe!
.pipe(take(1)).toPromise
firstValueFrom
and lastValueFrom
is definitly a better alternative for many reasons:
- The naming is more readable and self explanatory.
- The additional ability to select either first or last value.
- The additional ability to declare a default value in case the observable didn't emit any
Reference: https://stackoverflow.com/a/69215890/5191209
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
toPromise
appears in both questions... – Jonas Wilms Commented Aug 3, 2018 at 17:25