简体   繁体   English

承诺拒绝不适用于mysql错误

[英]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 . 我试图使用Promise返回一个mysql数据,并且可以正常工作,但是当我试图故意在mysql中创建错误时,却出现了这个错误。

(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. 我检查了所有地方,并说要使用.catch,但是奇怪的是我正在使用catch,但无法找出问题所在。 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 . 这就是我调用模型的方式,顶部的模型应该返回错误,因为mysql表被称为user而不是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. 应该创建返回承诺的函数,而不是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);
    });
});

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

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