网站搜索

typescript - 云函数在运行所有代码之前结束


我正在尝试创建一个云函数,但在 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;

  });

我认为问题在于函数在完成 for each 循环之前就返回了 0。

对此有解决方案吗?

谢谢!

答案#1

解决方案是在调用 return 之前等待所有异步 update() 操作完成:由于你使用了 forEach() 循环,你需要使用 Promise.all() 来等待循环中调用的所有异步操作完成,然后再返回它返回的 Promise。

如文档中所解释(上方链接),Promise.all()“通常在启动了多个异步任务并希望它们同时运行并为其结果创建了 Promise 之后使用,这样就可以等待所有任务完成。”

以下应该可以解决问题:

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)

    });

关于为什么在云函数中正确处理异步操作至关重要,我建议你观看 Firebase 视频系列中关于“JavaScript Promises”的 3 个视频:https://firebase.google.com/docs/functions/video-series/