Javascript 如何在等待时遍历Firestore快照文档

Javascript 如何在等待时遍历Firestore快照文档,javascript,node.js,firebase,google-cloud-firestore,google-cloud-functions,Javascript,Node.js,Firebase,Google Cloud Firestore,Google Cloud Functions,我一直在尝试从firestore获取一系列文档,阅读它们并根据一系列字段采取相应的行动。关键的部分是,在处理每个文档时,我想等待一个特定的过程。官方文档介绍了此解决方案: const docs = await firestore.collection(...).where(...).where(...).get() docs.forEach(await (doc) => { //something }) 这个解决方案的问题是,当你在forEach中有一个承诺时

我一直在尝试从firestore获取一系列文档,阅读它们并根据一系列字段采取相应的行动。关键的部分是,在处理每个文档时,我想等待一个特定的过程。官方文档介绍了此解决方案:

const docs = await firestore.collection(...).where(...).where(...).get()
    docs.forEach(await (doc) => {
      //something
    })
这个解决方案的问题是,当你在forEach中有一个承诺时,它不会在继续之前等待它,我需要它。我已尝试使用for循环:

const docs = await firestore.collection(...).where(...).where(...).get()
            for(var doc of docs.docs()) {
      //something
            }

使用此代码时,Firebase警告“docs.docs(…)不是函数或其返回值不可编辑”。关于如何解决这个问题有什么想法吗?

我找到了这个解决方案

const docs = [];

firestore.collection(...).where(...).get()
    .then((querySnapshot) => {
        querySnapshot.docs.forEach((doc) => docs.push(doc.data()))
    })
    .then(() => {
        docs.forEach((doc) => {
            // do something with the docs
        })
    })
正如您所看到的,这段代码将数据存储在外部数组中,并且只有在执行此操作之后,它才能处理该数据


我希望这能帮助你解决这个问题

请注意,
docs
变量是一个类型对象。它有一个名为的数组属性,可以像普通数组一样进行迭代。如果按如下方式重命名变量,则更容易理解:

const querySnapshot = await firestore.collection(...).where(...).where(...).get()
for (const documentSnapshot of querySnapshot.docs) {
    const data = documentSnapshot.data()
    // ... work with fields of data here
    // also use await here since you are still in scope of an async function
}

我刚刚测试了这个方法,它工作得很好,我的错误是使用.docs()而不是.docsIt的常规堆栈溢出来升级投票,并使用左侧的按钮接受正确的有用答案。