Trying to create a Google Cloud Function that reads Firestore Documents from a collection and takes action based on these documents. The goal is to optimize efficiency by reading the documents once and storing them in an array to minimize read operations. However, I am facing challenges in ensuring that the iteration over my array starts only after completing the reading process.
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")
})
});
Expected Output:
Matching invoked...
BPM: 120
Start loop
BPM: 120
Finish loop