firestore 查询等待嵌套 foreach 循环
我正在尝试使用集合中所有文档的名称填充一个数组,并使用这些父文档中的所有子集合文档填充另一个数组。
let data = []
let names = []
const suppliers = await db.collection('suppliers').get()
suppliers.forEach(async supplier => {
names.push({name: supplier.data().name, id: supplier.id })
const deliveries = await db.collection('suppliers').doc(supplier.id).collection('deliveries').get()
deliveries.forEach(delivery => {
data.push(delivery.data())
})
})
console.log(names) // Populated
console.log(data) // Empty
问题是它不等待内部循环完成就执行外部代码。 names
数组已填充,但 data
数组为空。如何在执行外部代码之前完成嵌套循环?
I'm trying to populate an array with names from all documents in a collection, and also populate another array with all the subcollection documents from those parent documents.
let data = []
let names = []
const suppliers = await db.collection('suppliers').get()
suppliers.forEach(async supplier => {
names.push({name: supplier.data().name, id: supplier.id })
const deliveries = await db.collection('suppliers').doc(supplier.id).collection('deliveries').get()
deliveries.forEach(delivery => {
data.push(delivery.data())
})
})
console.log(names) // Populated
console.log(data) // Empty
The problem is that it doesn't wait for the inner loop to finish before executing the code outside. The names
array gets populated but the the data
array is empty. How can i make the nested loop finish before executing the outside code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
加载供应商的交货是一个异步操作。由于您正在加载所有供应商的交货,并且只想在所有供应商加载完毕后进行记录,因此您需要等待多个异步操作,这需要使用
Promise.all
:Loading the deliveries for a supplier is an asynchronous operation. Since you're loading the deliveries for all suppliers and only want to log once all of them are loaded, you need to wait for multiple asynchronous operations, which requires the use of
Promise.all
:Foreach 不支持异步回调。为了摆脱这个,你可以使用。
Foreach doesn't support asynchronous callback. In order to get rid of this you can use.