为什么在Firebase Cloud Functions中无法删除此子节点?

时间:2018-10-09 17:27:50

标签: javascript node.js firebase firebase-realtime-database google-cloud-functions

我试图在事件节点过期后将其删除,并删除其所有子节点 image of the event node before getting removed

问题是当时间流逝并且我删除事件节点时,除该子节点外,所有子节点都将被删除

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

1 个答案:

答案 0 :(得分:0)

由于您多次调用了返回承诺的set()方法,因此您应该使用Promise.all()来等待所有承诺解决后再发送回响应。

下面的代码改编应该可以工作(但是未经测试):

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