I have this function which is called whenever a user types "/play" or "/register" to the bot and it's used for querying the database if the user has already his data store in the database or not.
I'm trying to make this function return true or false but it's not working as it should.. it always return false.
Hope someone can explain me why, thanks in advance! [I apologize for my bad english]
I tried to set the "let res = false" as a global variable, and change its value inside the callback function (which works, but only for the first time the method is executed [don't know why, would be fine if someone explains me this]).
I tried to initialize the variable inside the "isRegistered" function (as you can see in the code below) but the variable seems inaccessible inside the callback function.
function isRegistered(id){
let res = false;
db.all('SELECT iduser FROM users WHERE iduser = ?', [id], (err, rows) => {
if (err)
console.log(err);
if( rows != null)
res=true;
else res = false;
});
return res;
}
api.on('message', function(message) {
var chat_id = message.chat.id;
var text = message.text;
switch(text){
case '/register':
if (isRegistered(chat_id)){
api.sendMessage({
chat_id: message.chat.id,
text: 'You are already registered.'
});
}else{
insertRow(chat_id);
api.sendMessage({
chat_id: message.chat.id,
text: 'Now you are registered.'
});
}break;
....
....
}
}
I'm expecting that the callback function changes the value of the "res" variable.
I tried the code below and it's the only way to make it works. I don't understand why... I'm desperate
function isRegistered(id){
let res = false;
db.all('SELECT iduser FROM users WHERE iduser = ?', [id],(err, rows ) => {
if (err){
console.log(err);
}
rows.forEach( (row) => {
if(id == row.iduser) {
res = true;
}
});
});
return res;
}