Async/await on firebase queries

Again i’m asking for you help over firebase issues. For now i’ve put async/await to use the data from the snapshot outside my function but still doesent work:


        database.ref('adress').once('value', (snapshot) => {
            snapshot.forEach(async function (childSnapshot) {           
                 const childKey = await childSnapshot.key;
                 const childData = await childSnapshot.val();
                         
    });             
});


Can i get some help?

30 thoughts on “Async/await on firebase queries”

  1. I am not sure I follow your question fully, but using the example at https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document as a start point, we can rework the code to use await instead of then.

    var docRef = db.collection("cities").doc("SF");
    try {
      var doc = await docRef.get()
    
      if (doc.exists) {
        console.log("Document data:", doc.data());
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }
    } catch (err) {
        console.log("Error getting document:", error);
    }
    
    Reply
  2. I think you’re using async function in firebase wrong way

    you should using like this

    async funcion getAdress(){
      try{
         const snapshot = await database.ref('adress').once('value');
    
         snapshot.foreach();
      }catch(err){
         console.error(err);
      }
      
    }
    
    
    Reply

Leave a Comment