简体   繁体   English

未处理的 promise 拒绝使用 node.js

[英]Unhandled promise rejection using node.js

I have this code below and it is giving me an error saying that I have unhandled promise rejection.我在下面有这段代码,它给了我一个错误,说我没有处理 promise 拒绝。 I am new at node.js and express, I do not know what I did wrong.我是 node.js 和快递的新手,我不知道我做错了什么。

const User = require('../model/user');

const linkValidation = async (req, res, next)  => {
    var refer = req.params.refer;
    if (refer) {
        await User.findById(refer) 
        .then(user, async function() {
            if (user) {
                user.saldo = user.saldo + 10
                user.invites.push({
                nome: nome,
                valor_recebido: 10
                });
                await user.save().catch(err =>{
                    return res.status(500).json(err)
                })
            }else{
                return res.status(404).json({message: "Usuário que criou esse link não existe"})
            }
        }).catch(err =>{
        return res.status(500).json(err)
        })

    }else{

        return res.status(404).json({message: "Usuário que criou esse link não existe"})
    }
    next()
}

module.exports = linkValidation

The router I am using is:我使用的路由器是:

router.post('/cadastro/:refer', UserMiddleware, LinkMiddleware, UserController.create);

Can anyone help me?谁能帮我?

My main recommendation would be to only use async/await here.我的主要建议是在这里只使用 async/await。 I believe the way you are mixing async/await with.catch() and.then() is what is causing your error.我相信您将 async/await 与 .catch() 和 .then() 混合的方式是导致您的错误的原因。

When using async/await, I think it is simplest to just use the try/catch block (rather than.catch) as I have shown below, and pass any thrown error to your error handler with next in the catch block.使用 async/await 时,我认为最简单的方法是使用如下所示的 try/catch 块(而不是 .catch),并将任何抛出的错误传递给您的错误处理程序,并在 catch 块中使用 next。

For example...例如...

const User = require('../model/user');

const linkValidation = async (req, res, next)  => {
    try {
        const refer = req.params.refer;
        const user = await User.findById(refer) 

        if (user) {
            user.saldo = user.saldo + 10
            user.invites.push({
                nome: nome,
                valor_recebido: 10
            });
            await user.save()
        }

        res.send('success')

    } catch(err) {
        next(err)
    }
}

module.exports = linkValidation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM