簡體   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