Search code examples
mysqlnode.jspromisees6-promisebluebird

How to use promises to get result from mysql query in node.js


I have been using normal callbacks for getting mysql query to create a rest api for my application but the code became too complicated like this is the code of getting users profile

const con=require('../mysql.js');
     router.route("/profile")
            .post(checkjwt,(req,res,next)=>{
              try{
              var decoded = jwt.verify(req.body.token, config.secret);
              var mobile=decoded.mobile;



              if(mobile==null){
                res.json({
                  status:404,
                  message:'Please provide mobile Number'
             });
              }
              else{
                    var sql="select * from flavica_user where USER_MOBILE=?";
                con.query(sql,mobile,(err,result)=>{
                 if(err){
                  res.json({
                    status:204,
                    message:err.sqlMessage
               });
                 }
                 else if(result.length==0){
                  res.json({
                    status:404,
                    message:'No Data Found'
               });
                 }
            else if(result.length>0){
              res.json({
                status:200,
                message:result[0]
            });
            }

                });


              }
              }
              catch(err) {
                res.json({
                  status:404,
                  message:'Wrong Authorization token'
              });
              }



            })

I searched about bluebird promise library ,but the documentation was not quite clear about it .Any help regarding it will be appreciated.Thanks


Solution

  • You might want to use it like this somewhat

    var Promise = require("bluebird"); //use blue bird library after installing npm install bluebird
    
    const con=Promise.promisifyAll(require('../mysql.js'));
    
    router.route("/profile").post(checkjwt,(req,res,next)=>{
      try{
        var decoded = jwt.verify(req.body.token, config.secret);
        var mobile=decoded.mobile;
        var sql="select * from flavica_user where USER_MOBILE=?";
        con.queryAsync(sql,mobile).then(function(result){//bluebird identifies with Async
          res.json({
            status:200,
            message:result
          })
        }).catch(function(err){
          console.log(err);
        })
    
      }
      catch(err) {
      console.log(err);
      }
    });
    

    You can add your error handling sequences in between.I hope it help thanks