firebase中函数querysnapchot的变量中不能有数据

firebase中函数querysnapchot的变量中不能有数据,firebase,react-native,google-cloud-firestore,Firebase,React Native,Google Cloud Firestore,我的动作切换名称的函数querysnapchot中的变量nom中不能有我的数据。 querySnapshot.docs[0]。数据;当然有数据 var nom = ''; firebase.firestore().collection('Users').where("Id", "==",res.user.uid) .get() .then(function(querySnapshot) { if (querySnapshot.size > 0)

我的动作切换名称的函数querysnapchot中的变量nom中不能有我的数据。 querySnapshot.docs[0]。数据;当然有数据

    var nom = '';
    firebase.firestore().collection('Users').where("Id", "==",res.user.uid)
    .get()
    .then(function(querySnapshot) {
      if (querySnapshot.size > 0) {
        // Contents of first document
        nom = querySnapshot.docs[0].data();
      } else {
        console.log("No such document!");
      }
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

    console.log(nom);
    const action = { type: "TOGGLE_NAME", value: nom };
    this.props.dispatch(action)
    this.props.navigation.navigate('Navigation')

Firestore API是异步的,在查询完成之前立即返回。稍后调用then回调并返回结果。对于任何返回承诺的API来说,这基本上都是正确的


只能在回调中使用查询结果。您不能在查询之后的代码中使用它们,因为该代码将在查询完成之前立即执行。将依赖于查询结果的代码放在回调中。

Hey!能否在if部分添加注释?如果querySnapshot.size>0{nom=querySnapshot.docs[0].data;console.lognom;}我怀疑get函数是异步的,因此您的日志只是在结果存储到nom之前执行的。谢谢您的回答。我加了一个。然后在我的承诺和它的工作