0

i am using expressjs & postgresql

How to get parameter after query result in expressJS outside function

this is my code


const checkMail = function(regEmail){

      pool.query("SELECT * FROM tb_users where email=$1", [regEmail] ,(err, result) =>{

        console.log('inside : '+result.rowCount);       
        return result.rowCount;
      });
    
    }
    
    var cekMailres = checkMail(email);

    console.log('outside : '+cekMailres);

i need parameter result.rowCount

thank u for your help


my final solution


var email = req.body.email;

var cekMail = new Promise(function(resolve, reject) {
      pool.query("SELECT * FROM tb_users where email=$1", [email] , function(error,result) {
      console.log("Row count: %d",result.rows.length);  // n

      if(error){
          console.log(error)
      }
      
      resolve(result.rows.length);
      });  
  });

  cekMail.then(function (resolve, reject) {

    console.log(resolve);

    res.render('login/register',{

      layout: 'login/layout',
      mailStatus: resolve,
    });

  });

Community
  • 1
  • 1
dmforaname
  • 63
  • 1
  • 10

1 Answers1

1

You are not returning the value from the function (you are in the query callback). I have not tested this, but it should work like that:

const checkMail = async function(regEmail, fn){
  var rowCount = 0;
  await pool.query("SELECT * FROM tb_users where email=$1", [regEmail] ,(err, result) =>{

    console.log('inside : '+result.rowCount);
    fn(result.rowCount);       
    return result.rowCount;
  });

}

var cekMailres = checkMail(email, function(rowCount){
    console.log('Outside: ' + rowCount);
}).then(function () {
    //do nothing
}).catch(function () {
    //do nothing
});
frankenapps
  • 5,800
  • 6
  • 28
  • 69