等待时如何遍历Firestore快照文档 [英] How to iterate through a Firestore snapshot documents while awaiting
问题描述
我一直在尝试从Firestore获取一系列文档,阅读它们并根据一系列字段采取相应的行动.关键部分是我要在处理每个文档时等待特定的过程.官方文档介绍了此解决方案:
I have been trying to obtain a series of documents from firestore, reading them and acting accordingly depending on a series of fields. The key part is I want to wait for a certain process while working on each document. The official documentation presents this solution:
const docs = await firestore.collection(...).where(...).where(...).get()
docs.forEach(await (doc) => {
//something
})
当您在forEach中有一个承诺时,此解决方案的问题就解决了,它不会在继续之前等待它,而我需要它.我已经尝试过使用for循环:
The problem with this solution is taht when you have a promise inside the forEach it won't await it before continuing, which I need it to. I have tried using a for loop:
const docs = await firestore.collection(...).where(...).where(...).get()
for(var doc of docs.docs()) {
//something
}
使用此代码时,Firebase会警告"docs.docs(...)不是函数,或者其返回值不可迭代".关于如何解决此问题的任何想法?
When using this code Firebase alerts that 'docs.docs(...) is not a function or its return value is not iterable'. Any ideas on how to work around this?
推荐答案
请注意,您的 docs
变量是 docs 的数组属性,您可以对其进行迭代像普通数组一样.如果这样重命名变量,将会更容易理解:
Note that your docs
variable is a QuerySnapshot type object. It has an array property called docs that you can iterate like a normal array. It will be easier to understand if you rename the variable like this:
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
}
这篇关于等待时如何遍历Firestore快照文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!