Reputation: 148
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.
Upvotes: 0
Views: 178
Reputation: 68943
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';
});
}
});
.....
Upvotes: 1