gpt4 book ai didi

javascript - Firestore云函数查询数据库查询后返回值?

转载 作者:行者123 更新时间:2023-12-03 01:25:32 26 4
gpt4 key购买 nike

目前,我正在查询数据库中要更新的对象。执行此操作的函数片段是

 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 查询帖子后,将从实时数据库接收其他详细信息并将其添加到数组中。最后,我通过 promise 提交所有这些更新。但是,返回更新的函数永远不会到达 - 为了确保数据库需要更新,我有一个计数器来计算更新次数。如果大于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
}
})
})
})

最佳答案

admin.database().ref('/convoID/' + key).once(...) 是异步的并返回一个 promise ,但您的代码没有使用这些 promise 等待每个查询完成。这意味着您的代码在快照迭代之后、但在计数器更新或添加批处理之前立即转移到 if/else。

您需要重组代码以将所有这些 Promise 从 Once() 收集到一个数组中,使用 Promise.all() 等待所有这些 Promise 解决,然后提交批处理.

关于javascript - Firestore云函数查询数据库查询后返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51567704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com