我试图在事件 Node 过期后删除它并删除它的所有子 Node image of the event node before getting removed
问题是时间过去了,我删除了事件 Node ,除了这个 child 之外,所有的 child 都被删除了
image of the event node after getting removed
源代码
exports.removeOldEvents = functions.https.onRequest((req, res) => {
const eventsRef = admin.database().ref('events')
eventsRef.once('value', (snapshot) => {
snapshot.forEach((child) => {
child.forEach((child) => {
if (1000*Number(child.val()['endDate']) <= new Date().getTime()) {
child.ref.set(null)
}
})
})
})
return res.status(200).end()
})
最佳答案
由于您多次调用 set()
方法,它返回一个 promise ,您应该使用 Promise.all()
以便在发送回响应之前等待所有 promise 解决。
您的代码的以下改编应该有效(但未测试):
exports.removeOldEvents = functions.https.onRequest((req, res) => {
const eventsRef = admin.database().ref('events')
eventsRef.once('value')
.then((snapshot) => {
const promises = [];
snapshot.forEach((child) => {
child.forEach((child) => {
if (1000*Number(child.val().endDate) <= new Date().getTime()) {
promises.push(child.ref.set(null));
}
});
});
return Promise.all(promises);
})
.then(results => {
const responseObj = {response: 'success'};
res.send(responseObj);
})
.catch(err => {
res.status(500).send(err);
})
});
关于javascript - 为什么这个子 Node 在 Firebase Cloud Functions 中没有被删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52726393/