【问题标题】:service function firebase getDocs服务功能 firebase getDocs
【发布时间】:2022-07-27 02:17:46
【问题描述】:

我正在尝试构建一个 firestore get 函数来从 firestore 数据库中获取数据,我成功地将数据提取到控制台中,但我不知道如何返回数据,因为每次都会返回一个 promise。

export const getJobPostings = async () => {
  const jobPostingsRef = collection(database, "jobPostings");
  const snapShot = await getDocs(jobPostingsRef);
  snapShot.forEach((item) => {
    console.log(item.data());
  });
  return snapShot
};

【问题讨论】:

    标签: firebase google-cloud-firestore promise


    【解决方案1】:

    您没有展示如何调用此异步函数,但由于您解释了“每次(它)返回一个承诺”,您很可能没有正确调用它。

    由于 async 函数总是返回一个 Promise,您应该使用 then(),例如:

    getJobPostings()
    .then(snapShot => {
      snapShot.forEach((item) => {
        console.log(item.data());
      });
    });
    

    或在使用async 声明的异步 函数中使用await 调用它。

    export const anotherAsyncFunction = async () => {
      const snapShot = await getJobPostings();
      snapShot.forEach((item) => {
        console.log(item.data());
      });
    };
    

    【讨论】:

    • 谢谢Renaud,但我不想console.log数据,我想将获取的数据返回到一个变量,我应该在这个函数中怎么做?
    • 只有在then() 块内,您才能获得函数返回的QuerySnapshot 的值,该函数返回Promise。所以在这个块内,把值赋给变量。
    • 嗨@Nigel,您是否成功地如愿获得了获取的数据?
    【解决方案2】:

    按照@Renaud Tarnec答案中的线程,如果您想将获得的值保存在变量中,您只需创建一个变量并分配函数返回的值,在“getDocs”的情况下,它会为您带来一个firestore 集合中的一组元素,因此您必须创建一个数组类型变量并使用 foreach 传递响应以将值插入到所述变量中,如下所示:

    // let myVar = [] you can also declare the variable outside the function if you want to use the return value elsewhere
    
    getDocs(collection(db, 'jobPostings'))
      .then((response) => {
        let myVar = []
        response.forEach((doc) => {
          myVar.push(doc.data())
        });
        // console.log('My var:', myVar)
      })
      .catch((error) => {
        console.error(error)
      });
    

    【讨论】:

      猜你喜欢
      • 2018-11-02
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多