Search code examples
node.jsmongoosees6-promise

unhandle promise rejection warning. even though i added catch statement after then


I got an unhandle promise rejection warning when I'm saving to mondodb (with mongoose), but i implemented the catch statement. So I don't get why I have this warning.

Bellow my code, cheers.

--declaring the function with promise :

module.exports = {

getGameResult : () => {
    var gameResult = new GameResultModel();
    return new Promise((resolve, reject) =>{

        GameResultModel.find({}, function (err, docs){

            if (err) reject(err);
            if (!err) resolve(docs);

        });
    })

}

}

--calling the function :

 router.get("/all", (req, res) => {

databaseFunction.getGameResult()
    .then((result) => {
        res.send(result);
        res.sendStatus(200);
    })
    .catch((err) => {
        res.send(err);
        res.sendStatus(500);
    });

});


Solution

  • Try this:

    GameResultModel.find({}, function (err, docs){
        if (err) reject(err);
        if (!err) resolve(docs);
    }).catch(err => console.error("db.find has some error ", err));
    

    I recently had a similar issue and if this solution helps I would need to find for you the source where I found a good description of the issue and the resolution.