Usr
Usr

Reputation: 2838

javascript - "then" executing before the loop completes in firebase

EDIT: changed the code as suggested by the answer, using promises. It prints before Added all tags and then the various Found

I have the following code to fill an array with some keys from Firebase:

var userTags = [];
var arrayPromises = [];
user_pref.once('value', function(preferenze){ 
preferenze.forEach(function(t){
  ref.once('value', function(tags){ 
  arrayPromises.push(arrayPromises.push(new Promise(function (resolve, reject) {
  tags.forEach(function (t1){
    if(t.key == t1.key){ 
    console.log("Found " + t1.key)

    }
    return false;

  })}));
})
return false;
})
})
Promise.all(arrayPromises).then(()=>{
console.log("Added all tags")

})
}

I've added the then clause to be sure I call the method findPoiByTagis called after I filled the array, but apparently the code inside then is executed before the rest. In fact, the message lenght 2: is printed before the other message Lenght, with the consequence that it first prints "0" and then it prints the correct lenght while filling the array.

EDIT: it prints the lenght of the array a number of time equal to the number of forEach iterations, so the return false statement does not break the loop.

I've always used this method to wait for the instructions to be finished, why now is not working? Did I miss something?

Upvotes: 0

Views: 109

Answers (1)

LPZadkiel
LPZadkiel

Reputation: 571

oh well i see now, the then function is after the push function not afther the forEach so you will have to do something like this

var arrayPromises = [] 
forEach( 
push( 
... 
generatePromise 
... 
).then( 
... 
promiseRecieved 
checkForAllPromisesRecieved(doTheThing)
... ) ) 

function doTheThing(){
   this.myTags = userTags; 
   console.log("Lenght 2: " + userTags.length) 
   this.findPoiByTag(this.myTags);
}

Upvotes: 1

Related Questions