Rod
Rod

Reputation: 15475

Do I need the promise in my MySQL statement?

Below is a MySQL statement in my Node.js app. I used a promise in MySQL function to get API endpoint to work. Is this a typical pattern for Node.js and MySQL?

const express = require('express');
const app = express();

app.use(express.static('client'));
const config = require('./config')

var mysql = require('mysql');

var con = mysql.createConnection({
    host: config.HOST,
    user: config.USER,
    password: config.PASSWORD,
    database: config.DATABASE
});

function GetConsumers(req, res) {
    return new Promise(function (resolve, reject) {
        con.connect(function (err) {
            if (err) throw err;
            con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
                if (err) throw err;
                //console.log(result);
                resolve(result);
            });
        });
    }).then(rows => res.send(rows));
}

app.get('/consumers', GetConsumers);

module.exports = app;

Upvotes: 0

Views: 45

Answers (1)

Sreehari
Sreehari

Reputation: 1370

As George commented, you don't really need to return a promise here.

function GetConsumers(req, res) {

    con.connect(function (err) {
        if (err) {
           res.send(err)
        };
        con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
            if (err) {
               res.send(err)
           };
            //console.log(result);
            res.send(result)
        });
    });

}

If you really want to use promises, it is always a good practice to catch the exceptions.

function GetConsumers(req, res) {
return new Promise(function (resolve, reject) {
    con.connect(function (err) {
          if (err){
              reject(err);
          }

        con.query("SELECT * FROM " + config.DATABASE + ".Contracts", 
        function (err, result, fields) {
            if (err){
              reject(err);
            }
            //console.log(result);
            resolve(result);
        });
    });
})

}

Call GetConsumers function where ever you want it.

GetConsumers(req,res).then(rows => res.send(rows))
}).catch(err =>{ 
   console.log("Handle your error here");
   res.send("error")
})

Mysql npm has good documentation of how to use the module. You can refer it more here

Upvotes: 1

Related Questions