首页 > 解决方案 > Firebase await db.collection 不进入 catch 语句,永远等待

问题描述

我正在用 GatsbyJS 和 Firebase 制作一个小博客。我的博客是静态的,就像通常的 gatsby 博客一样,但我在 firebase 上获取评论数据。

这是我获取评论数据的功能

  //@@@ Fetch Comment Data function
 //function to fetch comment data 

 const fetchData = async () => {

   try {
           console.log("entered try")
           const commentRef = await db.collection("comments").doc(postID).get();
           setComments(commentRef.data().comments);
       } catch (error) {
           console.error(error);
      }
}

问题是,我试图写一个帖子没有评论的异常,也就是说文档 postID 不存在,我的 try catch 永远不会进入 catch 块,似乎它永远卡住了。我在这里想知道这是否是我的异步等待语法、我的一般函数语法或我正在打破的 Firestore 特定规则的错误。

如果文档存在,就好像我已经通过 firebase 面板创建了文档一样,这段代码可以正常工作,没有任何问题。所以我想加入 catch 语句,如果这个 postID 的文档不存在,我可以创建它或者至少 setState 来显示这个 postID 没有评论

谢谢

标签: javascriptfirebaseasync-awaittry-catch

解决方案


来自 firebase 文档:

以下示例显示如何使用 get() 检索单个文档的内容:

https://firebase.google.com/docs/firestore/query-data/get-data

var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

注意:如果 docRef 引用的位置没有文档,则生成的文档将为空,并且在其上调用存在将返回 false。

所以该get()方法永远不会抛出异常,这就是你的 catch 块没有运行的原因。在您的情况下,您将实现您的目标:

const fetchData = async () => {

const commentRef = await db.collection("comments").doc(postID).get().then(post => {

    try {
        if (!post.exists) {
           throw "Post doesn't exist";
        }
        setComments(post.data().comments);
    } catch (err) {
        console.error(err);
    }

});

}

代码未测试...


推荐阅读