Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have written a javascript code for fetching data from mysql database.

I have used connection pooling, and Promise API also.

the code is as follows,

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, in the above code ?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.