I have a Firebase Realtime database function running. The problem is that the foreach loop executes after the return return ref.child("/leaderboard").set(updates); I know i have to do something with Promise() ? But not sure how. Any ideas.
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);
});