我有一个Firebase实时数据库函数在运行,问题是foreach循环在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);
});
1条答案
按热度按时间uinbv5nw1#
是的,我按照this answer中的步骤解决了这个问题
像这样!