DEV Community

Cover image for Firestore Observables to Promises
Jonathan Gamble
Jonathan Gamble

Posted on • Edited on

Firestore Observables to Promises

Update 2/26/24

This post is out of date since Firebase 9. For latest Firebase posts, see Code.Build.


I am crazy, so I created a quick reference. Let me know if I missed one!

Note:

afa = AngularFireAuth
afs = AngularFirestore

but should be same premise in any framework.

Docs

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

or

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

or

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

or

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

But the shortest is:

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

Collections

const foo = await this.afs.collection('colPath').valueChanges()
.pipe((take(1))).toPromise();
Enter fullscreen mode Exit fullscreen mode

or

const foo = (await this.afs.collection('colPath').snapshotChanges()
.pipe(take(1)).toPromise()).map((m) => m.payload.doc.data());
Enter fullscreen mode Exit fullscreen mode

or

const foo = (await this.afs.collection('colPath').get()
.toPromise()).docs.map((m) => m.data());
Enter fullscreen mode Exit fullscreen mode

or (overkill from last version)

const foo = (await this.afs.collection('colPath').get()
.pipe(take(1)).toPromise()).docs.map((m) => m.data());
Enter fullscreen mode Exit fullscreen mode

or

const foo = (await this.afs.collection('colPath').ref.get())
.docs.map((m) => m.data());
Enter fullscreen mode Exit fullscreen mode

User

As you may have noticed...

const bar = await this.afa.currentUser;
Enter fullscreen mode Exit fullscreen mode

... does not load correctly in a lot of cases.

So try these:

const bar = await this.afa.authState.pipe(take(1)).toPromise();
Enter fullscreen mode Exit fullscreen mode

or (authstatechanged is most accurate)

const bar = await new Observable(
(observer: any) => { this.afa.onAuthStateChanged(observer) }
).pipe(take(1)).toPromise();
Enter fullscreen mode Exit fullscreen mode

or

const bar = await new Promise(
  (resolve: any, reject: any) =>
    this.afa.onAuthStateChanged((user) => {
      user ? resolve(true) : resolve(false);
    }, (e: any) => reject(e))
);
Enter fullscreen mode Exit fullscreen mode

or (the shortest)

const bar = await this.afa.user.pipe(take(1)).toPromise();
Enter fullscreen mode Exit fullscreen mode

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

J

Top comments (0)