【发布时间】: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