loading...

Firestore, get collection with async/await

gautemeekolsen profile image Gaute Meek Olsen Originally published at gaute.dev ・1 min read

Today I Learned how to get all documents in a collection in Firestore with async/await and for...of by using the .docs property.

Firebase documentation has examples with .then to get the result from a Promise.

const logCities = () => {
  let citiesRef = db.collection('cities');
  let allCities = citiesRef.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.id, '=>', doc.data());
      });
    })
}

But it can be written easier with async/await.

const logCities = async () => {
  let citiesRef = db.collection('cities');
  let allCities = await citiesRef.get();
  for(const doc of allCities.docs){
    console.log(doc.id, '=>', doc.data());
  }
}

I think this is more readable, two less lines and .docs allows us to use for of.

Discussion

pic
Editor guide
Collapse
chipd profile image
Chris Dermody

helped me a lot with some async problems I was having - and much more readable. thanks for sharing!