javascript await in foreach Firebase函数-对于返回后执行的每个循环

6za6bjd0  于 2023-02-15  发布在  Java
关注(0)|答案(1)|浏览(124)

我有一个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);
    });
uinbv5nw

uinbv5nw1#

是的,我按照this answer中的步骤解决了这个问题

async function printFiles () {
  const files = await getFilePaths();

  await Promise.all(files.map(async (file) => {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents)
  }));
}

像这样!

var data_snap_arr = [];
snapshot.forEach(child_Snapshot => {
    var stuff = child_Snapshot.val();
        stuff.key = child_Snapshot.key;
        data_snap_arr.push(stuff);
    });

    await Promise.all(data_snap_arr.map(handleSnapshot)).then(result => {
    const finalData = {};
    for (var i = 0; i < result.length; i++) {
        // process data here - data returned as array object
    }
    return ref.child("/leaderboard").set(finalData);
});

相关问题