Firebase async/await 查询未按预期工作

Firebase async/await query not working as expected

大家好,我对此有点陌生,但我会尽我所能解释它,所以我正在使用一个函数来 return 保证我的代码看起来像这样

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);
        });
    });
  }

我目前有两个帐户,一个是管理员,另一个是超级用户。问题是在获取 adminData 之前解决了承诺,可能是什么问题?

  • 您将 await 风格与 .then() 混合使用。完全摆脱 Promise.then,并坚持使用 async.
  • 您不能在 .forEach() 或任何其他数组方法(映射、过滤器等)中使用 await,但可以在 for 循环中使用。
  • accounts.push 完全同步,根本不需要await
    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");