【问题标题】:Firebase Functions Async forEach into forEachFirebase 函数异步 forEach 到 forEach
【发布时间】:2021-07-12 19:33:01
【问题描述】:

下面的代码扫描所有用户寻找要归档的节点:function archiveColab()

问题是该函数在扫描 /users/ 节点然后需要扫描 /collaborative 子节点的 forEach 内部,因此它有 另一个 forEach 内部 .

当我运行 arquivaColab 函数时,它会覆盖每月的每日记录,而不计算每个周期的总数,只留下该月的最后一个周期。

这是由于异步执行 forEach 造成的,我无法找到顺序读取和写入这些记录的方法。

添加等待/承诺时,显然循环在执行第一个循环/记录后结束。

我知道这是理解异步模式如何工作的问题,并且我已经尝试了几天找到解决方案。

非常欢迎任何帮助。

代码:

exports.todoDia = functions.runWith({memory: '1GB', timeoutSeconds: '300'}).pubsub.schedule('10 15 * * *').timeZone('America/Sao_Paulo').onRun( async () => {
    
    const cutoff = format(new Date().setDate(new Date().getDate() - 7), 'Y-m-d'); // 7 days ago
    var userRef = admin.database().ref("users");
    return userRef.once('value').then((snapshot) => {
        snapshot.forEach(user => {
            var userID = user.key;
            if (userID === "F54jCdsPt8ZLIF17dYn8U0knMMY2") { // Only this user for testing
                console.log(userID + " " + cutoff);
                user.child('collaborative').forEach(async collaborative => {
                    if (collaborative.key <= cutoff) { await arquivaColab(userID, collaborative.key, collaborative.val()); }
                });
            }
        });
        return null;
    });
});

async function arquivaColab(userID, keyColab, valColab) {
    console.log("userID: "+userID+" | keyColab: "+keyColab+" | valColab: "+valColab);
    const ref = admin.database().ref("/collaborative/"+userID+"/"+keyColab.substring(0,7));
    var stringDest = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0";
    return ref.once('value').then((snapDest) => {
        if (snapDest.exists()) { stringDest = snapDest.val() }

        var wordsOrig = valColab.split(" ");        
        var wordsDest = stringDest.split(" ");
    
        var strFinal = "";
        for (var i = 0; i < wordsOrig.length; i += 1) {    
            strFinal += (Number(wordsOrig[i]) + Number(wordsDest[i])) + " ";
        }
    
        console.log("DESTINO: /collaborative/"+userID+"/"+keyColab.substring(0,7)+" : "+strFinal);
        return admin.database().ref("/collaborative/"+userID+"/"+keyColab.substring(0,7)).set(strFinal.trim());
        // console.log("ORIGEM : /users/"+userID+"/collaborative/"+keyColab+" : "+valColab);
        // admin.database().ref("/users/"+userID+"/collaborative/"+keyColab.set(null);

    });
}

JSON:

  "users" : {
    "F54jCdsPt8ZLIF17dYn8U0knMMY2" : {
      "collaborative" : {
        "2021-03-12" : "0 0 0 0 0 0 1 0 0 2 0 0 0 0 0 0 0 0 0 0",
        "2021-03-15" : "0 0 0 0 0 0 1 0 0 2 0 0 0 0 0 0 0 0 0 0",
        "2021-07-07" : "0 0 0 0 0 0 0 2 0 1 0 0 0 0 0 0 0 0 0 0"
      },
      "username" : "John Doe"
    },
    "Z5EEkzyG2WPlCHa9a6gDpBnIr2u2" : {
      "collaborative" : {
        "2021-07-06" : "0 0 0 0 0 0 1 0 0 2 0 0 0 0 0 0 0 0 0 0",
        "2021-07-07" : "0 0 0 0 0 0 0 2 0 1 0 0 0 0 0 0 0 0 0 0"
      },
      "username" : "John Next"
    },
  },

要了解所需的功能: 每个用户都有一个名为“协作”的节点

YYYY-MM-DD:“0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0”

每天有 20 个计数器记录每个用户的不同活动。 7 天后,Firebase 函数必须将这些记录存档,计算每个计数器的总和,并在 /collaborative/userID/ 中的每月记录中计算。

【问题讨论】:

    标签: javascript firebase-realtime-database async-await google-cloud-functions


    【解决方案1】:

    forEach 不支持async/await。您需要将数据存储到一个数组中并使用支持async/awaitfor 循环,如下所示:

    return userRef.once("value").then(async (snapshot) => {
      const tempArray = [];
    
      if (userID === "F54jCdsPt8ZLIF17dYn8U0knMMY2") {
        // Only this user for testing
        console.log(userID + " " + cutoff);
        user.child("collaborative").forEach(async (collaborative) => {
          if (collaborative.key <= cutoff) {
            tempArray.push({
              userID,
              key: collaborative.key,
              val: collaborative.val(),
            });
          }
        });
      }
    
      for (let i = 0; i < tempArray.length; i++) {
        const { userID, key, val } = tempArray[i];
        await arquivaColab(userID, key, val);
      }
    });
    
    return null;
    
    

    【讨论】:

    • 成功了!我不得不对逻辑进行一些调整,但是将数据存储在数组中的建议概念正是我所需要的。非常感谢!
    猜你喜欢
    • 2016-08-17
    • 2013-07-25
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 2018-01-17
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多