Home » vue » Call a function after snapshot forEach with firebase

Call a function after snapshot forEach with firebase

Posted by: admin November 26, 2021 Leave a comment


I want to call an external function once the forEach have finished. This is the structure of my code:

  • export default
    1. mounted function
      • firebase foreach
        • here, once finished I want to call a methods function
    2. methods function
      • call computed function
    3. computed function

I think to use promise, but I don’t know how .

//inside the mounted function

//this is an aux vector, I want to push here the results of forEach
let aux = []

//here I'm login in firebase realtime database
firebase.auth().signInWithEmailAndPassword("user", "pass").then(function(user) {

    //here I want to read the database
    db.ref().once("value").then(function(snapshot) {

        //here I'm cycling on the fields of database
        snapshot.forEach(function(childSnapshot) {
          //here I'm saving the fields on the aux vector pushing them
          aux.push([childSnapshot.key, childSnapshot.val()])

        //here I want to call the UpdateFoto function but I cannot since the "this" is only defined out of all this firebase function

    }).catch(function(error) {
        console.log("Error getting document:", error);})
}).catch(function(error) {
      let errorCode = error.code;
      let errorMessage = error.message;
      console.log(errorCode +" "+errorMessage)})

//here I can access to "this" selector, but without a promise or something it is executed before the forEach will finish his loop. I want to call the function after the forEach have finished