承诺拒绝不使用mysql错误

我试图得到返回一个MySQL数据使用承诺,它的工作原理,但是当我尝试在目的地创build一个错误的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); }); }); 

您的模型文件中有错误。 返回承诺的函数应该被创build为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); }); });