【问题标题】:adding elements to array and then returning the value after forEach loop将元素添加到数组,然后在 forEach 循环之后返回值
【发布时间】:2019-09-09 00:30:05
【问题描述】:

我应该为移动用户访问一个名为“关注者”的子集合,其中包含关注者的 ID。 使用此 ID,我应该从 mobile_user 集合中获取有关追随者的数据并将其添加到数组中。 我可以成功地遍历文档列表,但是在使用 push 时,我似乎无法从 for 循环中返回完整的数据列表。

看看我当前的代码:

请注意两个控制台日志,在第一个上我可以看到数组充满了我想要的信息,在第二个上,数组返回为空。我肯定错过了从 for 循环中返回数组所需的任何内容。 我对js相当陌生,任何正确方向的建议都将不胜感激。

const getFollowers = (data, context) => { 
    let id = data.id 
    const mobileUserRef = db.collection('mobile_user')

    return mobileUserRef.doc(id).collection('followers')
    .get()
    .then(function(doc) { 
        var result = []
         doc.forEach(function(follower) { 
            mobileUserRef.doc(follower.id).get()
            .then(function(followerdoc) { 
                result.push({
                    name: followerdoc.data().name
                })
                console.log(result)
            })
        })
        console.log(result)
        return result 
    })
  }

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    mobileUserRef.doc(follower.id).get() 是异步的,并立即返回一个承诺。 forEach 循环在移动到列表中的快照之前不会等待该承诺解决。相反,您应该将该承诺推入一个数组,然后在该数组上使用 Promise.all 以等待所有获取完成,然后再继续。然后,您将不得不迭代每个结果并将它们推送到另一个数组中以提供给调用者。

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 2021-05-14
      • 2017-07-28
      • 2021-04-22
      • 2015-03-28
      • 1970-01-01
      • 2014-10-04
      相关资源
      最近更新 更多