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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 16, 2016 at 8:22
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

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

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Aug 8, 2017 at 4:12
\$\endgroup\$
2
  • \$\begingroup\$ Would you need to release on an error? \$\endgroup\$ Commented Aug 8, 2017 at 4:30
  • 1
    \$\begingroup\$ @StephenRauch Yes, as per the documentation, you need to release on an error. \$\endgroup\$ Commented Aug 8, 2017 at 5:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.