Firebase Cloud Function Cron Update



>我有函数,我正在使用基于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日志中收到此警告:

"函数返回未定义的预期承诺或值">

感谢您的任何帮助

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

解决方案是返回一个 promise,它只是一个对象,当您完成数据库时会发出信号。好消息是,once()update()都已经返回了承诺,因此您可以返回这些承诺:

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

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

最新更新