0

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
this.updateFoto(aux)
Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645
Andrea
  • 134
  • 2
  • 14

1 Answers1

2

Convert your functions to use the arrow function syntax, since they don't change the binding of this. So, instead of

function(snapshot) { ... }
function(childSnapshot) { ... }

Use

(snapshot) => { ... }
(childSnapshot) { ... }

If you use this syntax, this will remain unchanged from the outer scope, and you will be able to call this.updateFoto(aux) the way you originally wanted.

There is a lot of information about how JavaScript binds this in various situations. It will be helpful to learn how that works.

How does the "this" keyword work?

Doug Stevenson
  • 236,239
  • 27
  • 275
  • 302