NodeJS / React / Firestore-在状态中存储查询结果

时间:2019-03-19 17:50:32

标签: node.js reactjs google-cloud-firestore

function collectres () {
  var store ='';
  var docRef = db.collection("cities").doc("SF");
  docRef.get()
    .then(function (doc) {
      if (doc.exists) {
        console.log("Document data:", doc.data());
        store = doc.data();// when referenced outside, it doesnt hold anything.
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }
    })
    .catch(function (error) {
      console.log("Error getting document:", error);
    });
  return store; // returns nothing and seems to not notice the assignment.
}

我最初完成了一个简单的get,并希望将其存储在变量中。然后,我在index.js文件中添加了一个回调函数,因此可以调用此方法,然后对结果进行更多操作。 我的回调如下:

user.CollectRes(function(store){
      console.log(store.name);
      name =store.name;
      console.log(name);
     // this.setState({name:store.name});
    });
    console.log(name); // want to be able to reference this outside the callback function. So i can display it on the page.

我想知道如何获取查询结果并将其存储在状态中,以便可以在index.js文件中的任何位置引用它。

1 个答案:

答案 0 :(得分:0)

在代码中添加await语句将确保在函数返回未定义的store之前,存储调用完成,直到响应返回为止。

async function collectres () {
      var store ='';
      var docRef = db.collection("cities").doc("SF");
      docRef.get()
        .then(function (doc) {
          if (doc.exists) {
            console.log("Document data:", doc.data());
            store = await doc.data();// when referenced outside, it doesnt hold anything.
          } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
          }
        })
        .catch(function (error) {
          console.log("Error getting document:", error);
        });
      return store; // returns nothing and seems to not notice the assignment.
    }