简体   繁体   中英

promise reject not working with mysql error

I am trying to get return an mysql data using promises and it works, but when I try to create an error in mysql on purpose but then I am getting this error .

(node:28464) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Users not found
(node:28464) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I checked everywhere and it says to use .catch but its odd that I am using catch but cannot figure out the problem. Normally I would like to know how to solve this instead of just continuing without knowing the right way.

This is the model..

getAllUser =
     new Promise((resolve, reject) => {
        db.query('SELECT * from users', function (error, results, fields) {
            if (error){
                return reject('Users not found');
            }else{
                resolve(results[0]);
            }
        });
    });
module.exports = {
    getAllUser
};

And here is how I am calling the model, the model in the top should return an error since the mysql table is called user not users .

router.get('/db',(req,res,next)=>{
    getAllUser.then((result)=>{
      console.log(result);
    }).catch((e) => {
       console.log(e);
    });
});

You have error in your model file. Function which return promise should be created instead Promise.

Working code:

Model:

getAllUser = () => new Promise((resolve, reject) => {
    db.query('SELECT * from users', function (error, results, fields) {
        if (error){
            return reject('Users not found');
        }else{
            resolve(results[0]);
        }
    });
});
module.exports = {
    getAllUser
};

Router:

router.get('/db',(req,res,next)=>{
    getAllUser.then((result)=>{
      console.log(result);
    }).catch((e) => {
       console.log(e);
    });
});

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