繁体   English   中英

承诺拒绝不适用于mysql错误

[英]promise reject not working with mysql 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.

我检查了所有地方,并说要使用.catch,但是奇怪的是我正在使用catch,但无法找出问题所在。 通常,我想知道如何解决这个问题,而不是仅仅继续进行而不知道正确的方法。

这是模型。

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
};

这就是我调用模型的方式,顶部的模型应该返回错误,因为mysql表被称为user而不是users

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

您的模型文件中有错误。 应该创建返回承诺的函数,而不是Promise。

工作代码:

模型:

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.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