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?