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