0
I’m starting in Javascript and I’m creating a Whatsapp bot on Node.js and any block if
that I put does not work and always goes to else
.
It works that way:
- Get the message;
- Query the Sqlite database and check whether the number of the sender of the message is in the database and increases a variable (
cnt
); - A block
if
checks whether the variablecnt
is greater than0
, if no, it means that the number is not in the bank and adds it.
The problem is that the block if
doesn’t work, always returning else
.
I’ve tried to use if (+cnt > +0)
, I tried using an array, putting all the numbers on it and using a arr.includes(message.author)
, but I get the same mistake, nothing I put in if
works.
Am I forgetting something? It has to do with the database?
function start(client) {
client.onMessage(async message => {
db.serialize(function() {
var cnt = 0
db.each(`SELECT phone as phone, xp as xp, admin as admin, lastmsg as lastmsg, msgcount as msgcount FROM users`, (err, row) => {
if (err) {
console.error(err.message);
}
if (Object.is(row.phone, message.author)) {
cnt++;
}
console.log(message.author + " - " + row.phone + " - " + cnt)
})
if (+cnt > +0) {
console.log(`Usuario ${message.author} já existe na database.`);
}
else
{
db.serialize(function() {
db.run(`INSERT INTO users (phone,xp,admin,lastmsg,msgcount) VALUES ("${message.author}",0,0,0,0)`);
console.log(`Usuário ${message.author} adicionado a database.`);
})
}
});
});
}
I believe that
db.each
is an asynchronous function, so thisif/else
below should be within the function of callback.– Cmte Cardeal
if (+cnt > +0)
- you don’t need those+
(this is a way to convert strings to numbers, but bothcnt
how much0
are already numbers, so this+
is really unnecessary there)– hkotsubo