Im using the firebase admin SDK server-side, and in one of my routes, im getting a collection, and then looping over each document in said collection...during each iteration, i use a property value to do a second get(). in the then() of this secondary get(), i again use data from the initial get to make final, tertiary get().
unfortunately the asynchronous nature of these nested calls seems to be creating undesirable outcomes.
heres the route function:
router.get('/list', authorization, (req, res) => {
console.log('/reports/list entered...')
admin
.firestore()
.collection('user-reports')
.get()
.then(querySnapshot => {
const reports = []
querySnapshot.forEach(snapshotDocument => {
const closed = snapshotDocument.get('closed')
console.log(`closed status: ${closed}`)
if (closed === false) {
const data = snapshotDocument.data()
console.log(`condition passed, data: ${JSON.stringify(data)}`)
// get # of reports made by sender
admin
.firestore()
.collection('users')
.doc(data.reportee)
.get()
.then(doc => {
data['reportee'] = {
reportActivity: doc.get('reportActivity')
}
console.log(`first then => data; ${JSON.stringify(data)}`)
// get report history of reportee
admin
.firestore()
.collection('users')
.doc(data.reporter)
.get()
.then(doc => {
data['reporter'] = {
reportActivity: doc.get('reportActivity')
}
console.log(`second then, ${JSON.stringify(data)}`)
reports.push(data)
})
.catch(err => {
return res.json({ error: true, message: err })
})
})
.catch(err => {
return res.json({ error: true, message: err })
})
}
})
console.log(`pre-response: ${JSON.stringify(reports)}`)
return res.json({ reports })
})
.catch(err => res.json({ error: true, message: err }))
})
what im logging is the "first condition passed", "pre-response: []", and "first then => data". by the time i ultimately return "reports" its empty. is there a more effective way to run firestore methods inside of foreach loops?
question from:
https://stackoverflow.com/questions/66056095/how-to-make-asynchronous-calls-inside-of-a-firestore-foreach-loop 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…