0

I am trying to do a simple if-else in NodeJS.

as per the information about the syntax it looks correct.

However no matter what if block is not working. Neither the msg variable value is getting updated.

Code:

sql.connect(config, function(err) {
console.log(err)
var r = new sql.Request();
r.input('gc', sql.VarChar, gcode);
r.input('ingt',sql.VarChar, gtype);
r.input('incf',sql.VarChar,gconfig);
r.input('ingp',sql.VarChar, gprovider);
r.input('inld',sql.DateTime2, launchdate)
r.input('in_activefrom',sql.DateTime2, date_activeFrom)
r.input('in_activeto',sql.DateTime2, date_activeTo)
r.multiple = true;

var rec_count = 0;
r.query("select * from md.GameMasters WHERE gameCode=@gc",function(err, result){
    rec_count = result['recordset'].length;
    console.log('Existing Records: ' + rec_count)
})

if(Number(rec_count) >0){
    console.log('Multiple record exist')
    msg = "Record Exist in Database";
}
else{
    r.query("INSERT INTO md.GameMasters(gameCode,gtype,config,grovider,launchdate,activefrom,activeto,recordEntryOn) VALUES(@gc,@ingt,@incf,@ingp,@inld,@in_activefrom,@in_activeto,getdate())",function(err,result){
        console.log(result['rowsAffected'][0])
        console.log('Record Inserted')
    })
    msg = 'Record Added';
}

});

Wanted to know what part went wrong.

Aman Khandelwal
  • 148
  • 1
  • 13
  • 1
    Does this answer your question? [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) – AZ_ Dec 05 '19 at 09:31
  • i don't think so. I saw the answer but can't co-relate – Aman Khandelwal Dec 05 '19 at 09:33
  • It's the same, you just can't correlate. :). Simply you cannot access the variable outside of callback without using the following methods explained in the post. – AZ_ Dec 05 '19 at 09:37
  • Everything you want to happen after the query has finished needs to be moved inside the `function(err, result)` callback. It's very much a duplicate of that question. It's a *very* common issue, and easily identifiable. –  Dec 05 '19 at 11:17

1 Answers1

1

Being query() is asynchronous your if...else is executing way before the variable is updated, include that inside call back function:

......
r.query("select * from md.GameMasters WHERE gameCode=@gc",function(err, result){
  rec_count = result['recordset'].length;
  console.log('Existing Records: ' + rec_count);

  if(Number(rec_count) >0){
    console.log('Multiple record exist')
    msg = "Record Exist in Database";
  }
  else{
    r.query("INSERT INTO md.GameMasters(gameCode,gtype,config,grovider,launchdate,activefrom,activeto,recordEntryOn) VALUES(@gc,@ingt,@incf,@ingp,@inld,@in_activefrom,@in_activeto,getdate())",function(err,result){
        console.log(result['rowsAffected'][0])
        console.log('Record Inserted');
        msg = 'Record Added';
    });
  }
});
.....
Mamun
  • 66,969
  • 9
  • 47
  • 59