panchester
panchester

Reputation: 335

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?

Upvotes: 0

Views: 150

Answers (1)

Nicky
Nicky

Reputation: 26

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

Upvotes: 1

Related Questions