首页 > 解决方案 > NodeJs / React-如何将来自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.

标签: node.jsgoogle-cloud-firestore

解决方案


这是因为 JavaScript 是异步的。

因此,您的变量在您的函数doc之外尚不存在。.then

要返回这个值,你可以使用Promises方式,或者更简单,你可以有一个回调函数来返回你的文档,如下所示:

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
});

我建议您阅读这篇文章以了解有关异步的更多信息。

希望能帮助到你。


推荐阅读