【问题标题】:Firestore code is not waiting for responseFirestore 代码不等待响应
【发布时间】:2020-06-20 08:33:37
【问题描述】:

我是 React Native、Javascript 和 Firestore 的新手。问题是我正在尝试读取 firestore 数据库并等待响应以在下一页上显示信息,然后再呈现。

这是控制器代码:

  _signIn = async () => {
    try {
      // Google sign in and connect to Firebase
         ... This code is working as expected
      // Connect to the Firebase Firestore and store the connection
        CesarFirestore.setFirestore(firebase.firestore());
        let cFS = CesarFirestore.getInstance();
        cFS.saveLoginDetails(this.cUser);
     // THIS IS THE CALL TO GET THE STATUS OF THE USER
        await cFS.readAvailability(this.cUser);
        this.setState({loggedIn: true});
      } else {
        ... INVALID login coding works fine 
      }
    } catch (error) {
      ... CATCH coding works fine
      }
    }
  };

从上面标记的行开始,执行以下代码:

  async readAvailability(cUser) {
    let tuesdayDate = new CesarDate().getTuesday();
    let availableRef = CesarFirestore.getFirestore().collection('available');
    let availableQuery = await availableRef
      .where('tuesdayDate', '==', tuesdayDate)
      .where('userId', '==', cUser.getUserId())
      .get()
      .then(snapshot => {
        if (snapshot.empty) {
          console.log('No matching documents.');
          cUser.setTuesdayAvailability('NOT_FOUND');
        }
        snapshot.forEach(doc => {
          cUser.setTuesdayAvailability(doc.get('status'));
        });
      })
      .catch(err => {
        console.log('Error getting documents', err);
      });
  }

所以 readAvailability(cUser) 代码应该等待 availableQuery 返回结果。然后将结果存储在 cUser 类中,该类可供应用程序的其余部分使用。

有时结果可用,有时结果为空。我认为这是因为 doc 未定义,我已通过调试器确认。

任何帮助都会很棒,并在此先感谢您

【问题讨论】:

    标签: javascript react-native google-cloud-firestore async-await


    【解决方案1】:

    如果你 await 一个函数,它必须返回一个值,或者一个稍后解析为一个值的承诺。由于您使用的是 Promise(在您的 then() 处理程序中),因此解释器无法知道要等待什么。

      async readAvailability(cUser) {
        let tuesdayDate = new CesarDate().getTuesday();
        let availableRef = CesarFirestore.getFirestore().collection('available');
        let snapshot = await availableRef
          .where('tuesdayDate', '==', tuesdayDate)
          .where('userId', '==', cUser.getUserId())
          .get()
        if (snapshot.empty) {
          console.log('No matching documents.');
          cUser.setTuesdayAvailability('NOT_FOUND');
        }
        snapshot.forEach(doc => {
          cUser.setTuesdayAvailability(doc.get('status'));
        });
        return true; 
      }
    

    实际上我通常会让readAvailability 返回它修改的用户,但上面的方法也应该可以。

    【讨论】:

    • 感谢您的快速回复和帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多