I'm working on counting subscribers numbers in users/campaigns on Firebase Cloud Function. But the error occurs when the result total numbers runs faster than running total numbers.
export const howManySubscribers = async () => {
await firestoreRef
.collection('users')
.get()
.then((userQuerySnapshot) => {
userQuerySnapshot.forEach((userDoc) => {
if (!userDoc) return
userDoc.ref
.collection('campaigns')
.get()
.then(async (campaignQuerySnapshot) => {
await campaignQuerySnapshot.forEach(async (campaignDoc) => {
const subscribersNumber = await campaignDoc.ref
.collection('subscribers')
.get()
.then(async (subscriberQuerySnapshot) => {
return await subscriberQuerySnapshot.size
})
totalSubscribersNumber =
totalSubscribersNumber + subscribersNumber
// running total numbers
console.log('running total numbers', totalNewSubscribersNumber)
})
// result total numbers
console.log('result total numbers', totalNewSubscribersNumber)
})
})
})
}
awaitit. async/await doesn't work in a forEach lambda function the way you're expecting it to.async awaitand what problem it is trying to solve. You are mixing these with.thencalls a lot, which makes your code pretty hard to understand. I strongly suggest either fully sticking toasync awaitor not using it at all.