如何从Firebase函数的forEach循环返回单个变量?

时间:2019-03-09 16:14:43

标签: javascript firebase firebase-realtime-database google-cloud-functions

我创建了一个使用Firebase的iOS应用,并编写了一个Firebase云功能,该功能在应用中有新项目(发布)时向所有应用用户发送通知。我不希望用户收到太多通知,因此Firebase函数还将通知时间保存到数据库中。触发该功能后,它将检索上一次通知的时间,并且仅在经过最短时间(当前为24小时)后才发送新通知。

我的问题是从forEach循环内部检索一个变量,特别是上次通知时间的值(以下代码中的变量'epoch2')。我看不到forEach循环之外的值。我花了几个小时尝试解决这个问题,包括尝试将值推送到在循环外声明的数组。但是即使这样也行不通,一旦退出循环,该值就不可见。

我唯一可以使用的解决方案是将其余的代码(第二个forEach循环遍历所有用户并发送通知)放在第一个forEach循环中。我的代码如下。从技术上讲,这可以完成我想要的工作,但是感觉很笨拙,而且似乎不是“正确”的方法。

是否有更好/更简单的方法从第一个forEach循环中检索单个值,然后该值在其余函数中仍然可见?我将不胜感激。

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// function to send notification when there is a new post
exports.sendNotification = functions.database.ref('/posts/{postId}').onCreate((snapshot, context) => {

  // current time
  var epoch1 = Math.round((new Date()).getTime() / 1000);

  // retrieve time of last notification from database
  admin.database().ref("notifications").orderByKey().limitToLast(1).on('value', function(snap1) {
    snap1.forEach(function(childNodes1) {

      var epoch2 = childNodes1.val().date;

      var timeSinceLastNotification = epoch1 - epoch2;

      // only send new notification if it has been at least 24 hours since last one
      if (timeSinceLastNotification >= 86400) {

        var payload = {
          notification: { title: 'New Post', body: 'A new post is available' }
        };

        // loop through all users
        admin.database().ref("users").on('value', function(snap2) {

          snap2.forEach(function(childNodes2) {

            var fcmToken = childNodes2.val().fcmToken;

            // only send a notification if they have an fcmToken in the database
            if (fcmToken) {
              // SEND NOTIFICATION
            }
          })
        })

        // record notification in the database
        var newNotification = admin.database().ref('notifications').push();
        newNotification.set({
          'date': epoch1
        });

      }
    })
  })
})

0 个答案:

没有答案