【问题标题】:javascript - "then" executing before the loop completes in firebasejavascript - 在firebase中循环完成之前执行“then”
【发布时间】:2017-12-12 14:35:41
【问题描述】:

编辑:使用承诺更改了答案所建议的代码。它在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 子句以确保在填充数组后调用findPoiByTagis 方法,但显然then 中的代码在其余部分之前执行。事实上,消息lenght 2: 是在另一条消息Lenght 之前打印的,其结果是它首先打印“0”,然后在填充数组时打印正确的长度。

编辑:它打印数组的长度等于 forEach 迭代的次数,因此return false 语句不会中断循环。

我一直用这种方法等待指令完成,为什么现在不起作用?我错过了什么吗?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

    哦,我现在明白了,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);
    }
    

    【讨论】:

    • 如果我删除“return false”,它会给我一个错误,说我必须返回一个布尔值。
    • 我之前用过这段代码,和这个一样,Firebase的使用需要这个构造。当返回 false 时,它​​通常不会停止,因为它需要它。此外,如果它真的会在第一次迭代后返回,那么它将只打印一次数组的长度,而不是在每次迭代时打印它。
    • 哦,我现在明白了,then 函数在 push 函数之后,而不是在 forEach 之后,所以你必须执行类似 var arrayPromises = [] forEach( push( ... generatePromise .. . ).then( ... promiseRecieved ... ) ) //毕竟承诺 this.myTags = userTags; console.log("长度 2:" + userTags.length) this.findPoiByTag(this.myTags);
    • 我改变了答案:)
    • 谢谢!我不确定如何使用 Promise,我已经更改了问题中的代码,以向您展示我是如何使用它们的,因为它不能像我那样正常工作:\
    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2020-12-03
    相关资源
    最近更新 更多