javascript - Google Firestore promise

标签 javascript firebase promise google-cloud-firestore eslint

我目前正在尝试研究如何使用 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/

相关文章:

javascript - 为什么 yield 被归类为运算符而不是语句?

javascript - 使用 Node 的 `response.end` 方法和 promise

javascript - 在 Angular 中绑定(bind) JSON 数据

javascript - Vue : Why does computed property require . 在商店中声明时 v-model 指令中的值,但在组件中声明时不存在

Firebase:进入页面后停止刷新数据

firebase - 一个项目中有多个应用程序,或者Firebase中每个应用程序中有一个项目?

javascript - 类型错误 : Cannot call method 'click' of undefined

javascript - Deferred 和/或 Promise 数组的 jQuery.when() 进度

javascript - 选择任何一个单选按钮后,单选按钮选项卡焦点无法正常工作

firebase - firestore云函数onCreate/onDelete有时会立即触发两次