问题描述
我正在尝试创建一个云功能,但是在firebase的日志中,它在完成所有任务之前显示为完成".
I'm trying to create a cloud function, but it in the logs of firebase, it shows 'finished' before doing all the tasks.
这是我的代码.
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;
});
我认为问题在于函数在完成每个循环的操作之前会返回0.
I think the problem is that the function returns 0 before finishing the for each loop.
对此有解决方案吗?
谢谢!
推荐答案
解决方案是在调用return之前等待所有异步 update()
操作完成:因为您使用的是 forEach()
循环,您需要使用 Promise.all()
,以便在返回的Promise之前等待循环中调用的所有异步操作完成.
The solution is to wait for all the asynchronous update()
operations to be completed before calling return: since you use a forEach()
loop, you need to use Promise.all()
in order to wait for all the asynchronous operations called in the loop to be completed before returning the Promise it returns.
如文档(上面的链接)中所述, Promise.all()
通常在启动多个异步任务并发运行并为结果,以便人们可以等待所有任务完成."
As explained in the doc (link above), Promise.all()
"is typically used after having started multiple asynchronous tasks to run concurrently and having created promises for their results, so that one can wait for all the tasks being finished".
以下应该可以解决问题:
The following should do the trick:
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/
这篇关于云功能在运行所有代码之前结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!