【发布时间】:2019-01-05 03:41:38
【问题描述】:
目前,我正在查询数据库中要更新的对象。这样做的函数的 sn-p 是
return getPostsForDate.get().then(snapshot => {
const updates = {}
var counter = 0
const batch = admin.firestore().batch()
snapshot.forEach((doc) => {
var key = doc.id
return admin.database().ref('/convoID/' + key).once('value', (snapshot) => {
if (snapshot.exists()) {
const convoIDCollection = snapshot.val()
for (var child in convoIDCollection) {
console.log(child)
updates["conversations/" + child] = null
updates["messages/"+ child] = null
updates["convoID/"+ child] = null
}
}
updates["/convoID/" + key] = null
updates["/reveals/" + key] = null
updates["/postDetails/" + key] = null
const postFireStoreRef = admin.firestore().collection('posts').doc(key)
const posterRef = admin.firestore().collection('posters').doc(key)
batch.delete(postFireStoreRef)
batch.delete(posterRef)
counter++
console.log(counter)
})
})
if (counter > 0) {
console.log("at the deletion point")
return Promise.all[admin.database().ref().update(updates), batch.commit()]
}
else {
console.log("null")
return null
}
})
本质上,在 firestore 查询帖子后,会从实时数据库接收更多详细信息并将其添加到数组中。最后,我通过一个承诺提交所有这些更新。但是,永远不会到达返回更新的函数——为了确保数据库需要更新,我有一个计数器来计算更新的数量。如果大于0,我返回
return Promise.all[admin.database().ref().update(updates), batch.commit()]
但是,返回函数似乎是在收到其他详细信息之前执行的,因为它不断将“null”返回到控制台日志,只有当计数器小于 0 时才会发生这种情况。
本质上,如何在执行更新之前等待查询数据?
更新
return getPostsForDate.get().then(snapshot => {
const updates = {}
const promises = []
var counter = 0
const batch = admin.firestore().batch()
snapshot.forEach((doc) => {
promises.push (
admin.database().ref('/convoID/' + key).once('value', (snapshot) => {
if (snapshot.exists()) {
const convoIDCollection = snapshot.val()
for (var child in convoIDCollection) {
updates["conversations/" + child] = null
updates["messages/"+ child] = null
updates["convoID/"+ child] = null
}
}
updates["/convoID/" + key] = null
updates["/reveals/" + key] = null
updates["/postDetails/" + key] = null
const postFireStoreRef = admin.firestore().collection('posts').doc(key)
const posterRef = admin.firestore().collection('posters').doc(key)
batch.delete(postFireStoreRef)
batch.delete(posterRef)
counter++
})
)
})
Promise.all(promises).then(() => {
if (counter > 0) {
console.log("at the deletion")
return Promise.all[admin.database().ref().update(updates), batch.commit()]
}
else {
console.log("null")
return null
}
})
})
})
【问题讨论】:
标签: javascript node.js firebase google-cloud-functions