我正在尝试创建一个谷歌云函数,它读取一组 Firestore 文档并执行这些文档的操作。这些文档应该被读取一次并存储在一个数组中以减少所需的读取操作。但是我无法做到正确,以便在完成阅读部分后开始对我的数组进行迭代。
export const matchUsers = functions
.region("europe-west1")
.pubsub
.topic("matchUsers")
.onPublish(async message => {
console.log("Matching invoked...")
await firebase.firestore().collection("matchData").listDocuments().then(docRefs => {
const docs: admin.firestore.DocumentData[] = []
docRefs.forEach(async docRef => {
await docRef.get().then(snapshot => {
const data = snapshot.data()
if (data) {
console.log("BPM: " + data.bpm) # gets called
docs.push(data)
}
})
})
console.log("Start loop")
docs.forEach(doc => {
console.log("BPM: " + doc.bpm) # never gets called
})
console.log("Finish loop")
})
});
输出:
Matching invoked...
Start loop
Finish loop
BPM: 120
我希望输出是: 输出:
Matching invoked...
BPM: 120
Start loop
BPM: 120
Finish loop
试试这个:
export const matchUsers = functions
.region("europe-west1")
.pubsub
.topic("matchUsers")
.onPublish(async message => {
console.log("Matching invoked...")
await firebase.firestore().collection("matchData").get().then(docRefs => {
const docs: admin.firestore.DocumentData[] = []
docRefs.forEach(docRef => {
const data = docRef.data()
console.log("BPM: " + data.bpm) # gets called
docs.push(data)
})
console.log("Start loop")
docs.forEach(doc => {
console.log("BPM: " + doc.bpm)
})
console.log("Finish loop")
})
});
看起来您正在将异步与同步操作混合在一起,并且它没有按照您期望的方式工作,get()
对于这种情况也足够了。
最后,如果您的收藏量很大,请注意超时。
祝你好运
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句