Firebase Database Snapshot ForEach Async Await

Viewed 8746

async/await doesn't seem to work with firebase forEach. This code runs console.log for the first child of the snapshot and then just hangs. Is this a bug or am I missing something?

main()
async function main() {
  const snap = await root.ref('somepath')
    .once('value')

  snap.forEach(async val => {
    await console.log(val.key)

  })
}
2 Answers

I use something like this:

import * as admin from "firebase-admin";

type FunctionOnDataSnapshot = (childSnapshot: admin.database.DataSnapshot) => Promise<any>;
export const asyncForEach = async (dataSnapshot: admin.database.DataSnapshot, childFunction: FunctionOnDataSnapshot) => {
    const toWait = [];
    dataSnapshot.forEach(childSnapshot => {
        toWait.push(childFunction((childSnapshot)));
    });
    await Promise.all(toWait);
};
Related