3
\$\begingroup\$

I have written JavaScript code for fetching data from a MySQL database. I have used connection pooling and Promise API.

var mySql = require("mysql");
var Promise = require("promise");

var pool = mySql.createPool({
  host : "localhost",
  user : "root",
  password : "rahul",
  database : "testDb", //schema 
  connectionLimit : 13, // at a time 13 connection be created in pool
});

function getDepartments(){
  return new Promise(fn);

  function fn(resolve,reject){
    pool.getConnection(function(err,con){
        if(err){
            return reject(err);
        }else{
            con.query("select * from departmentTbl",function(err,rows){
                if(err){
                    return reject(err);
                }else{
                    con.release(); // releasing connection to pool
                    return resolve(rows);
                }
            }); 
        }
      }); // getConnection
    }// fn
 } // getDepartments

getDepartments().then(function(rows){
  console.log(rows);    
}).catch(function(err){
  console.log(err); 
}).done(function(){
  pool.end();   // closing all connections in pool
});

Can I further improve the code? I have only used one Promise. Can I use multiple promises to avoid callback hell?

\$\endgroup\$
0
3
\$\begingroup\$

Resource leakage: put con.release() outside the else block.

\$\endgroup\$
2
  • \$\begingroup\$ Would you need to release on an error? \$\endgroup\$ – Stephen Rauch Aug 8 '17 at 4:30
  • 1
    \$\begingroup\$ @StephenRauch Yes, as per the documentation, you need to release on an error. \$\endgroup\$ – mdfst13 Aug 8 '17 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.