如何从异步函数中导出/读取数据,该函数查询firebase

发布于 2025-02-13 00:01:30 字数 1168 浏览 0 评论 0原文

通过创建项目来学习如何使用反应。

我正在尝试通过将其添加到集合中来过滤数据。然后,我试图在一定时间内添加所有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何以心动 2025-02-20 00:01:31

尝试一下:

而不是:

await db...

=&gt;

return db...

运行不需要成为异步函数,

run().then(totalCalories => console.log('totalCalories :', totalCalories));

现在运行返回承诺,当解决此诺言时,它会返回DB查询

完整代码返回的总标准:

function run() {
    const time = 48;
    const timediff = moment(new Date()).subtract(time, "hours")._d;
    return db // this is returned by the function (as a promise)
      .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; //this is returned by db query
      })
      .catch(function (error) {
        console.log("Error getting documents: ", error);
      });
  }

// if your code is an ES6 module
let result = await run(); 
console.log('Result :', result);

// else
run().then(result => console.log('Total : ', result));

// to export this as ES6 Module
export { run }
// or
export default run;

要返回所有数据 +计算的值totalcalories,您可以做:

return { ...doc.data(),  'totalCalories': totalCalories };

Try this :

Instead of :

await db...

=>

return db...

run doesn't need to be an async function anymore

run().then(totalCalories => console.log('totalCalories :', totalCalories));

Now run return a promise, when this promise is resolved it return the totalCalories returned by your db query

Full code :

function run() {
    const time = 48;
    const timediff = moment(new Date()).subtract(time, "hours")._d;
    return db // this is returned by the function (as a promise)
      .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; //this is returned by db query
      })
      .catch(function (error) {
        console.log("Error getting documents: ", error);
      });
  }

// if your code is an ES6 module
let result = await run(); 
console.log('Result :', result);

// else
run().then(result => console.log('Total : ', result));

// to export this as ES6 Module
export { run }
// or
export default run;

To return all the data + calculated value totalCalories you can do :

return { ...doc.data(),  'totalCalories': totalCalories };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文