我目前正在尝试研究如何使用 Firestore 和 NodeJS 进行基本查询。我收到错误“预期 catch() 或返回”。我希望有人能解释为什么会发生这种情况?
我正在使用快速路由器来处理路由。
方法1.ESLint错误
userRouter.get("randomroutename", (req, res) => {
const uid = req.params.uid;
console.log("User: " + uid);
let collectionRef = db.collection('col');
collectionRef.add({foo: 'bar'}).then(documentReference => {
console.log(`Added document with name: ${documentReference.id}`);
res.status(200).send('SUCCESS');
});
});
环顾四周并尝试了一些方法后,这似乎有效,但我真的很困惑为什么需要返回。对我来说,当函数“add”肯定返回我可以访问 .then 的 promise 时,为什么我需要返回一个 promise ,这对我来说真的没有意义。
方法2.没有错误
userRouter.get("randomroutename", (req, res) => {
const uid = req.params.uid;
console.log("User: " + uid);
let collectionRef = db.collection('col');
return collectionRef.add({foo: 'bar'}).then(documentReference => {
console.log(`Added document with name: ${documentReference.id}`);
return res.status(200).send('SUCCESS');
});
});
根据文档 ( https://googleapis.dev/nodejs/firestore/latest/CollectionReference.html ),我相信方法 1 应该有效。
感谢您的帮助! (非常抱歉,如果这是显而易见的,我只是无法理解它......)
最佳答案
该消息显示“预期 catch() 或返回”。请注意,这里有两个选择。如果您想将 promise 的责任传递给调用者,那么使用 return 是合适的,但这不是您想要做的。相反,您应该做的是捕获 then
返回的 promise 捕获的任何潜在错误,并适本地处理它们:
collectionRef.add({foo: 'bar'}).then(documentReference => {
console.log(`Added document with name: ${documentReference.id}`);
res.status(200).send('SUCCESS');
}).catch(err => {
res.status(500);
})
这样,如果由于任何原因添加文档时出现错误,它将向客户端生成 500 响应。
这并不是 Firestore 独有的。这只是处理 ESLint 试图让您做的 promise 的最佳实践。
关于javascript - Google Firestore promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57732815/