javascript-“然后"在Firebase中的循环完成之前执行 [英] javascript - "then" executing before the loop completes in firebase
问题描述
使用承诺更改了答案所建议的代码.它先打印Added all tags
,然后打印各种Found
changed the code as suggested by the answer, using promises. It prints before Added all tags
and then the various Found
我有以下代码用Firebase的一些键填充数组:
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")
})
}
我添加了then
子句以确保在填充数组后调用方法findPoiByTag
,但是显然then
中的代码在其余代码之前执行.实际上,消息lenght 2:
在其他消息Lenght
之前打印,结果是它先打印"0",然后在填充数组的同时打印正确的长度.
I've added the then
clause to be sure I call the method findPoiByTag
is 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.
它打印数组的长度等于forEach迭代次数的时间,因此return false
语句不会中断循环.
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?
推荐答案
哦,我现在知道了,那么then函数是在push函数之后,而不是forEach之上,因此您将必须执行以下操作
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);
}
这篇关于javascript-“然后"在Firebase中的循环完成之前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!