javascript - 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 没有评论
谢谢
解决方案
来自 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);
}
});
}
代码未测试...
推荐阅读
- python-3.x - 如何从 jupyter notebook 访问 HUE?
- vb.net - vb.net Randomising 独特的按钮设置按钮?
- vb.net - 如何在 VB.net 中创建 Win 应用程序设置时询问许可证文件
- javascript - 计算每个数组项的出现次数并将结果作为对象返回
- flutter - 如何在颤动的列表视图中显示广告?
- tensorflow - 部署我通过 Colab Google 创建的 Tiny ML 模型
- c# - 如何使用 PrincipalContext 将用户添加到 Active Directory 中的组
- email - 将调查中的电子邮件发送到odoo12中的电子邮件列表时重新加载错误
- python - python webdriver_manager chrome 自定义配置文件
- javascript - 如何在 App Center 崩溃报告中查看未缩小的 React Native JS 调用?