【问题标题】:Firebase async/await query not working as expectedFirebase 异步/等待查询未按预期工作
【发布时间】:2021-07-15 10:55:56
【问题描述】:

嘿伙计们,我对此有点陌生,但我会尽我所能解释它,所以我使用一个函数来返回一个承诺,我的代码看起来像这样

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 之前已解决的承诺,可能是什么问题?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore async-await es6-promise


    【解决方案1】:
    • 您正在将await 样式与.then() 混合使用。完全摆脱Promise.then,并坚持使用async
    • 您不能在 .forEach() 内使用 await 或任何其他 Array 方法(映射、过滤器等),但可以在 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");
    

    【讨论】:

    • 按照您的建议将forEach 换成for 循环后,它就像一个魅力......谢谢!
    猜你喜欢
    • 2019-04-19
    • 2020-03-04
    • 2019-04-07
    • 2022-01-22
    • 2018-12-02
    • 1970-01-01
    • 2021-12-08
    • 2023-03-03
    • 2019-08-31
    相关资源
    最近更新 更多