【发布时间】:2021-02-28 21:48:19
【问题描述】:
我有一个 Firebase 实时数据库函数正在运行。问题是foreach循环在return return ref.child("/leaderboard").set(updates);之后执行我知道我必须对 Promise() 做点什么?但不确定如何。任何想法。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// Checks the weekly scores and creates a leaderboard entry of the top 3
exports.insertLeaderboard = functions.database.ref('/challenges/weekly/{weeklyId}/scores/{userId}')
.onWrite(async (change) => {
const ref = change.after.ref.parent.parent; // reference to the parent
const leaderboardItems = ref.child("scores").orderByChild('score').limitToLast(3);
const snapshot = await leaderboardItems.once('value');
var updates = snapshot.val();
snapshot.forEach(async element => {
const playerRef = admin.database().ref("players/" + element.key + "/playerProfile");
await playerRef.once('value', (result) => {
if (result.exists) {
console.log("Found Element:" + result.key);
updates[element.key]["name"] = result.child("DisplayName").val();
} else {
console.log("NOT Found Element:" + element.key);
}
});
});
console.log("Doing Final Write");
return ref.child("/leaderboard").set(updates);
});
【问题讨论】:
-
async 无法按照您对 forEach 循环回调函数的预期方式工作。我建议阅读:stackoverflow.com/questions/37576685/…
-
这能回答你的问题吗? Using async/await with a forEach loop
标签: javascript firebase firebase-realtime-database async-await google-cloud-functions