我正在尝试创建一个云函数,但它在 firebase 日志中,在执行所有任务之前显示“已完成”。
这是我的代码。
export const count = functions.pubsub
.schedule('0 8 * * *')
.timeZone('Europe/Brussels')
.onRun(async context => {
const snapshot = await admin.database().ref('/counter').once('value');
snapshot.forEach( (child) =>
{
var info = child.val();
var dayViews = info['count'];
var ID = child.key;
var ref1 = admin.database().ref('/counter/'+ID);
ref1
.update({
"count": 0,
"totalViews": dayViews,
})
.then(function() {
console.log("Write completed")
}).catch(function(error) {
console.error("Write failed: "+error)
});
});
return 0;
});
我认为问题在于该函数在完成 foreach 循环之前返回 0。
有针对这个的解决方法吗?
Thanks!
解决方案是等待所有异步update()
在调用 return 之前要完成的操作:因为您使用forEach()
循环,你需要使用Promise.all() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all为了等待循环中调用的所有异步操作完成后再返回它返回的 Promise。
正如文档(上面的链接)中所解释的,Promise.all()
“通常在开始后使用多个异步任务同时运行并为他们的结果做出承诺,以便人们可以等待所有任务完成”。
以下应该可以解决问题:
export const count = functions.pubsub
.schedule('0 8 * * *')
.timeZone('Europe/Brussels')
.onRun(async context => {
const snapshot = await admin.database().ref('/counter').once('value');
const promises = [];
snapshot.forEach((child) => {
var info = child.val();
var dayViews = info['count'];
var ID = child.key;
var ref1 = admin.database().ref('/counter/' + ID);
promises.push(ref1
.update({
"count": 0,
"totalViews": dayViews,
}));
});
return Promise.all(promises)
});
关于为什么正确处理 Cloud Function 中的异步操作至关重要,我建议您观看 Firebase 视频系列中有关“JavaScript Promises”的 3 个视频:https://firebase.google.com/docs/functions/video-series/ https://firebase.google.com/docs/functions/video-series/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)