0

Hey guys I'm abit new to this but I'll explain it the best way I can, So I'm using a function to return a promise my code looks something like this

getAccounts(email) {
    return new Promise((resolve, reject) => {
      usersCollection.where('email', '==', email).where('userType', 'in', ['Admin', 'Superuser'])
        .get()
        .then(async querySnapshot => {
          const accounts = [];
          await querySnapshot.forEach(async account => {
            let accountData = await account.data();
            accountData.id = accountData.userType;
            if (accountData.userType === 'Admin') {
              const adminObj = new Admin();
              const adminData = await adminObj.getAdminDetails();
              accountData = { ...accountData, ...adminData };
            }
            accountData.uid = authId;
            await accounts.push(accountData);
          });
          resolve(accounts);
        });
    });
  }

I currently have two accounts, one Admin, the other Superuser the problem is the promise resolved before adminData can be fetched, what could be the issue?

kengeene
  • 17
  • 6

1 Answers1

2
  • You are mixing await style with .then(). Get rid of Promise and .then entirely, and stick with async.
  • You can't use await inside .forEach() or any other Array method (map, filter, etc) but you can inside a for loop.
  • accounts.push is perfectly synchronous, no need to await it at all.
    const getAccounts = async email => {
    
        const querySnapshot = await usersCollection
                                .where('email', '==', email)
                                .where('userType', 'in', ['Admin', 'Superuser'])
                                .get();
    
        const accounts = [];
    
        for( let account of querySnapshot.docs ){
            let accountData = await account.data();
            accountData.id = accountData.userType;
            if (accountData.userType === 'Admin') {
                const adminObj = new Admin();
                const adminData = await adminObj.getAdminDetails();
                accountData = { ...accountData, ...adminData };
            }
            accountData.uid = authId;
            accounts.push(accountData);
        }
    
        return accounts;
    }

    const accounts = await getAccounts("some.email@domain.com");
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • 1
    After swapping the ``forEach`` for a ``for`` loop just like you recommended, it worked like a charm...thanks! – kengeene Apr 22 '21 at 10:27