简体   繁体   中英

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. I am new at node.js and express, I do not know what I did wrong.

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. I believe the way you are mixing async/await with.catch() and.then() is what is causing your error.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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