1

I’m trying to create a simple node script to do an export of my firebase auth and storage data. I’ve tried with something like this, but the output is not respecting the async order I’m expecting. Can anyone see if I’m doing something wrong?

// omitting imports

const firestore = admin.firestore();

const main = async () => {
  const listUsersResult = await admin.auth().listUsers(10);

  await Promise.all(listUsersResult.users.map(async user => {
    console.log(user.uid);

    try {
      const marketsQuerySnapshot = await firestore.collection(`users/${user.uid}/markets`).get();
      console.log(marketsQuerySnapshot.size);
      await Promise.all(marketsQuerySnapshot.docs.map(async result => {
        console.log(result.data());
      }));
    } catch (e) {
      console.error(e);
    }
  }));
};

main();

As result I’m having all the userId first and then all the markets, but using async I’m expecting to have userId, then markets of that user, and then other userId, etc.

Using the debugger I can see that after const marketsQuerySnapshot = await... the function "return" and the console.log(marketsQuerySnapshot.size); is executed asynchronously, but there is not return. I can't understand.

Thanks

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Davide C
  • 830
  • 2
  • 11
  • 21
  • `but there is not return`, where? – ikhvjs Aug 24 '21 at 14:24
  • The admin SDK isn't complicating matters at all. You have essentially the same problem as the duplicate, except you are using map to iterate instead of a foreach loop. You have many alternatives documented as answers there. – Doug Stevenson Aug 24 '21 at 14:24
  • Why are you using Promise.all `listUsersResult`? `admin.auth().listUsers(10);` it must be returning the user's info. You should check how Promise.all works with async/await. – Apoorva Chikara Aug 24 '21 at 14:27
  • 1
    @ApoorvaChikara In the provided code, `Promise.all` is being used against the array of promises returned by `map` (not the original array `listUsersResult.users`). Notice that the map lambda is `async`, which means each item of the list will be a promise. – Doug Stevenson Aug 24 '21 at 14:43

0 Answers0