javascript - Firebase 云函数 Cron 更新

标签 javascript firebase google-cloud-functions

我有一个函数,用于根据 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 或值”

感谢您的帮助

最佳答案

由于您的 Cloud Function 不返回值,因此 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 知道您的代码在 }) 之后仍然有效,因为您返回了一个 promise 。然后,当您的 update() 完成时,它会解析它返回的 promise ,并且 Google Cloud Functions 可以关闭容器(或者至少:停止向您收取其使用费用)。

关于javascript - Firebase 云函数 Cron 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52461508/

相关文章:

javascript - 如何使程序在不重新输入的情况下恢复为原始文本

javascript - DOB 的 JQuery 日历可在月、年或日期更改时反射(reflect)更改

python 在异步回调中调用 django 的渲染函数不起作用

python - 导入错误 : cannot import name language in Google Cloud Language API

mysql - 将 Cloud Function (nodejs) 连接到 CloudSQL mySQL 数据库

firebase - Stripe firebase扩展,监听收集组中的发票收集

java - 将 JS 变量传递给 java 类

javascript - 如何动态为元素jquery的数据属性编号?

database - Firestore文档引用,你能扩展文档服务器端吗?

javascript - 如何在 strip 中保存卡详细信息(javascript)