javascript - “then” executing before the loop completes in firebase

前提是你 提交于 2020-01-06 08:08:15

问题


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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/47775150/javascript-then-executing-before-the-loop-completes-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!