0

i am trying to set values of array within a function but that array show blank outside of that function.

router.post('/',function(req,res){
    var resultData= Array();
    getBirthDates(function(result){
        if(result.length>0)
        resultData = result;
        console.log('inside -- > ');
        console.log(resultData);
    });
    console.log('outside -- > ');
    console.log(resultData);
});

function getBirthDates(callback){
    var sqlBirthDays = "SELECT displayName, DATE_FORMAT((userDob),'%m-%d') AS DOB, DATE_FORMAT(NOW(),'%m-%d') TD  FROM mx_admin_user HAVING DOB = TD";
    con.query(sqlBirthDays, function (err, result, fields) {
        if (err) throw err;
        return callback(result);
    });
 }
  • Most likely the good ol behavior of asynchronous nature of nodejs. Use "then" for any operation that call database – Loredra L Feb 04 '19 at 14:15
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – AKX Feb 04 '19 at 14:28
  • Try `console.log(result)` after `con.query`? – molamk Feb 04 '19 at 14:29
  • @LoredraL `then` won't help – those aren't promises but callbacks. – AKX Feb 04 '19 at 14:29

1 Answers1

0

It is because query takes some time to perform and statement outside the block calls immediately

Updated Code:

router.post('/',function(req,res){
    var resultData= Array();
    getBirthDates(function(result){
        if(result.length>0)
        resultData = result;
        console.log('inside -- > ');
        console.log(resultData);
    });
    // Add timer function
    setTimeout(function() {
      console.log('outside -- > ');
      console.log(resultData);
    }, 3000)
});

function getBirthDates(callback){
    var sqlBirthDays = "SELECT displayName, DATE_FORMAT((userDob),'%m-%d') AS DOB, DATE_FORMAT(NOW(),'%m-%d') TD  FROM mx_admin_user HAVING DOB = TD";
    con.query(sqlBirthDays, function (err, result, fields) {
        if (err) throw err;
        return callback(result);
    });
 }
Riaz Ahmed
  • 37
  • 1
  • 2
  • it works.. thank you.. but i want a proper way to do this kind of stuff in node js. please suggest how can i do that without setTimeout function. – Shubham Wagh Feb 05 '19 at 13:40