【问题标题】:Firebase Cloud Function Cron UpdateFirebase 云函数 Cron 更新
【发布时间】:2019-02-26 21:54:59
【问题描述】:

我有基于 Cron Job 对我的数据库进行更新的功能。看起来是这样的(值得一提的是我在这里得到了很多帮助)

exports.minute_job =
  functions.pubsub.topic('minute-tick').onPublish((event) => { 

    var ref = admin.database().ref("comments")
    ref.once("value").then((snapshot) => {
        var updates = {};
        snapshot.forEach(commentSnapshot => {
            var comment = commentSnapshot.val();

            var currentRating = comment.rating - comment.lastRating;          
            var newScore = ((Math.abs(comment.internalScore) * 0.95) + currentRating) * -1;

            if(newScore < 0.000001) { newScore = 0.000001}

            updates[commentSnapshot.key + "/lastRating"] = comment.rating;
            updates[commentSnapshot.key + "/internalScore"] = newScore;         
        });

        ref.update(updates);
    })
  });

一切正常,除了我从 Firebase 日志中收到此警告:

“函数返回未定义的、预期的 Promise 或值”

感谢您的帮助

【问题讨论】:

    标签: javascript firebase google-cloud-functions


    【解决方案1】:

    由于您的 Cloud Functions 不返回值,因此 Google Cloud Functions 引擎包含不知道代码何时完成。在许多情况下,这意味着 GCF 将在关闭 }) 执行后立即终止包含您的函数。但此时,您的代码可能仍在从数据库中加载数据,而且肯定还没有更新数据库。

    解决方案是返回一个 Promise,它只是一个在您完成数据库时会发出信号的对象。好消息是 once() 和 update() 都已经返回了 Promise,所以你可以返回它们:

    exports.minute_job =
      functions.pubsub.topic('minute-tick').onPublish((event) => { 
    
        var ref = admin.database().ref("comments")
        return ref.once("value").then((snapshot) => {
            var updates = {};
            snapshot.forEach(commentSnapshot => {
                var comment = commentSnapshot.val();
    
                var currentRating = comment.rating - comment.lastRating;          
                var newScore = ((Math.abs(comment.internalScore) * 0.95) + currentRating) * -1;
    
                if(newScore < 0.000001) { newScore = 0.000001}
    
                updates[commentSnapshot.key + "/lastRating"] = comment.rating;
                updates[commentSnapshot.key + "/internalScore"] = newScore;         
            });
    
            return ref.update(updates);
        })
      });
    

    现在 Google Cloud Functions 知道您的代码在 }) 之后仍然有效,因为您返回了一个承诺。然后当您的update() 完成时,它会解析它返回的承诺,Google Cloud Functions 可以关闭容器(或至少:停止向您收取使用费)。

    【讨论】:

    • 再次感谢弗兰克,如果没有你,我真的永远不会把它放在一起。看来现在一切正常,非常感谢。
    猜你喜欢
    • 2017-11-13
    • 2017-12-08
    • 2018-06-12
    • 2018-11-30
    • 2021-02-18
    • 2017-09-05
    • 2023-04-02
    • 2019-01-18
    • 2020-06-21
    相关资源
    最近更新 更多