编辑:使用 promise 更改了答案所建议的代码。它在 Added all Tags
之前打印,然后打印各种 Found
我有以下代码来使用 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”,然后在填充大批。
编辑:它打印数组长度的次数等于 forEach 迭代的次数,因此 return false
语句不会中断循环。
我一直用这个方法来等待指令完成,为什么现在不起作用?我错过了什么吗?
最佳答案
哦,我现在明白了,then 函数是在 push 函数之后,而不是在 forEach 之后,所以你必须做这样的事情
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 - "then"在 firebase 中循环完成之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47775150/