NodeJs / React-如何将来自Firestore的查询结果存储在变量中

时间:2019-03-19 14:36:01

标签: node.js 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.
}

我有这个问题,我想将Firebase查询结果存储到一个变量中。但是,当我尝试从查询中为变量分配一些数据时,似乎无法存储它。 任何在正确方向上的帮助或建议都会有所帮助。

编辑1: 实现回调函数后,我想知道如何设置组件的状态或永久存储结果,以便许多组件可以访问它。

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.

1 个答案:

答案 0 :(得分:0)

It is because JavaScript is asynchrone.

Because of that, your variable doc doesn't exists yet outside your .then function.

To return this value, you can use Promises way, or easier, you can have a callback function to return your document like this :

function collectres (callback) {
    var docRef = db.collection("cities").doc("SF");
    docRef.get().then(function (doc) {
        if (doc && doc.exists) {
            callback(doc.data()); // Return your data inside the callback function
        } else {
            callback(null); // Return null if data doesn't exists
        }
    }).catch(function (error) {
        callback(null); // Return null in error case
    });
}

collectres(function (store) { // Call collectres to get your data
    console.log(store);
    // continue here
});

I recommand you to read this article to learn more about asynchronous.

Hope it helps.