【问题标题】:Unhandled promise rejection in express route快递路线中未处理的承诺拒绝
【发布时间】:2018-02-02 19:06:54
【问题描述】:

我收到此错误:

UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):错误:发送后无法设置标头。

从我的快速路线路线的这一部分:

router.post('/', jsonParser, (req, res) => {

    // checking that given id is valid

    let { id } = req.body; 

    User.findById({ id })
        .count()
        .then(count => {
            if (count < 1) {
                return Promise.reject({
                    code: 422, 
                    reason: 'Validation Error', 
                    message: 'Family must be created by a user', 
                    location: 'id'
                })
            } 
            return resolve(); 
        })
        .catch(err => {
            return res.status(err.code).json({code: err.code, message: err.message, reason: err.reason, location: err.location })
        }); 

    ...

我不擅长承诺。有人可以在这里看到我做错了什么吗?

【问题讨论】:

  • 你已经在一个 promise 回调中。所以你应该使用 throw 而不是 reject。

标签: node.js express mongoose


【解决方案1】:

resolveundefined,你可以使用 return count 代替,将数据传递给下一个 Promise:

User.findById({ id })
        .count()
        .then(count => {
            if (count < 1) {
                throw new Error('Family must be created by a user')
            } 
            // success
            return count;
        })
        .then( res => { // res will be count if the promise not rejected
             res.json({ success: true, count: res })
        })
        .catch(err => {
            return res.status(422).json({
                code: 422, 
                reason: 'Validation Error', 
                message: 'Family must be created by a user', 
                location: 'id'
            })
        });

【讨论】:

  • 是的,我尝试了 Promise.resolve() 位,但仍然无法正常工作。很奇怪。
  • 尝试使用 @notionquest 评论所描述的 throw,我更新了我的答案
  • 我实际上还有更多的路线,所以我还不想使用 res。这只是路线中实际工作开始之前的检查
  • 这只是一个检查,以确保真正的用户正在创建一个 fmaily。在检查 id 是否有效后,我创建了一个家庭。因此,如果我像上面那样使用 res,我将被退出整个路线,这不是我想做的事情
  • 我明白了,你可以使用return语句将数据发送到下一个promise链
【解决方案2】:
.catch(err => { return res.status(err.code).json({code: err.code, message: err.message, reason: err.reason, location: err.location }) });

这就是问题所在。发送响应时,您不能发送另一个响应。所以当你这样做时

res.status(), express 发送带有状态码的响应。并且 .json() 会给出异常。

尝试像这样设置状态。 res.statusCode = 代码;然后 res.json()

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2023-03-17
    • 2018-04-01
    • 2021-09-19
    • 1970-01-01
    相关资源
    最近更新 更多