如何从异步函数中导出/读取数据,该函数查询firebase
通过创建项目来学习如何使用反应。
我正在尝试通过将其添加到集合中来过滤数据。然后,我试图在一定时间内添加所有 totalcalories ,以便我可以使用React以形式显示它。
但是,我不知道如何获得 TotalCalories 的价值,也可以获取其他领域,例如用餐时间。我想在我的 app.js 中显示所有这些内容,但是当我这样做时,我会变得不确定,或者说承诺待定。
任何帮助将不胜感激。 谢谢
firebase.js
export async function run() {
const time = 48;
const timediff = moment(new Date()).subtract(time, "hours")._d;
await db
.collection("/food/meals")
.where("mealTime", ">=", timediff)
.get()
.then((qSnapshot) => {
let totalCalories = 0;
qSnapshot.forEach(function (doc) {
totalCalories += doc.data().calories;
console.log(doc.id, " -> ", doc.data());
});
console.log(totalCalories);
return totalCalories;
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
}
run(); //returns nothing
console.log(run()); //Promise {<pending>}
console.log(run().totalCalories); //undefined
Learning how to use react by creating a project.
I am trying to filter the data by when it was added into the collection. Then I am trying to add all the totalCalories in a certain amount of time so i can display it in form using react.
However, I do not know how to get the values for totalCalories and also get the other fields like mealTime. I want to display all of them in my app.js However when i do i get undefined, or says promise pending.
Any help would be massively appreciated. Thanks
firebase.js
export async function run() {
const time = 48;
const timediff = moment(new Date()).subtract(time, "hours")._d;
await db
.collection("/food/meals")
.where("mealTime", ">=", timediff)
.get()
.then((qSnapshot) => {
let totalCalories = 0;
qSnapshot.forEach(function (doc) {
totalCalories += doc.data().calories;
console.log(doc.id, " -> ", doc.data());
});
console.log(totalCalories);
return totalCalories;
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
}
run(); //returns nothing
console.log(run()); //Promise {<pending>}
console.log(run().totalCalories); //undefined
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试一下:
而不是:
=&gt;
运行不需要成为异步函数,
现在运行返回承诺,当解决此诺言时,它会返回DB查询
完整代码返回的总标准:
要返回所有数据 +计算的值totalcalories,您可以做:
Try this :
Instead of :
=>
run doesn't need to be an async function anymore
Now run return a promise, when this promise is resolved it return the totalCalories returned by your db query
Full code :
To return all the data + calculated value totalCalories you can do :