node.js - 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.
解决方案
这是因为 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
});
我建议您阅读这篇文章以了解有关异步的更多信息。
希望能帮助到你。
推荐阅读
- android - 如何设置 endpt.disable_tcp_switch 配置?
- ns-3 - 如何在 NS-3 中使用 TCP 获取丢失数据包的数量?(80211n + MIMO 示例)
- javascript - FullCalendar-v4 allDay 事件未呈现
- python - Django ModelFormSet 单击“提交”保存表单但不更新到数据库
- amazon-web-services - 如何 Terraform 规划多个 AWS 账户,然后审核,然后应用到多个账户
- swift - 在服务器上存储密码
- javascript - 应用程序已加载时 PWA 更新服务工作者
- maven - 如何强制 Maven 使用特定的存储库(仅此而已)?
- javascript - 有没有办法让屏幕 100% 的高度和宽度,但是当按比例缩小时总是足够大以包含子元素
- flask - 如何在 python 包的烧瓶静态文件夹中动态保存?