我正在尝试创建一个Google Cloud Function,以读取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
答案 0 :(得分:0)
尝试一下:
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()
足以满足要求。
最后,请注意是否超时(超时)。
祝你好运