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)
})
})
})
}