Reputation: 43
im writing a discord bot to check points from a database then return them. This is my code at the moment.
function userCheck(id, name) {
date = new Date().toISOString().slice(0, 19).replace('T', ' ');
con.query("SELECT id FROM users WHERE id = "+id, function (err, row) {
if (!(row && row.length) ) {
con.query("INSERT INTO `users` (id,name,rank,points,signup) VALUES ('"+id+"', "+name+", '0', '0' , '"+date+"')"), function (err, result, fields){
if (err) throw err;
}
}else{
//fine
}
});
}
function checkPoints(user){
id = user.id;
name = con.escape(user.username);
userCheck(id, name);
console.log("SELECT points FROM users WHERE id = "+id);
con.query("SELECT points FROM users WHERE id = "+id, function (err, result, fields){
return result[0].points;
});
}
My code which calls these functions is this:
return message.author.send(checkPoints(message.author));
This makes discordjs error as it is trying to return an empty message. This means my functions arent returning right. Ive look at this over and over its probably just a simple fix but I cant see it.
Thanks in advance
Upvotes: 0
Views: 171
Reputation: 6264
function checkPoints(user){
doesn't return anything i.e. same as return undefined
Since con.query is asynchronous - the simplest fix is to use a callback, like so
function checkPoints(user, cb){
id = user.id;
name = con.escape(user.username);
userCheck(id, name);
console.log("SELECT points FROM users WHERE id = "+id);
con.query("SELECT points FROM users WHERE id = "+id, function (err, result, fields){
cb(result[0].points);
});
}
checkPoints(message.author, function(result) {
message.author.send(result);
});
or, use Promise
function checkPoints(user){
return new Promise(function(resolve, reject) {
id = user.id;
name = con.escape(user.username);
userCheck(id, name);
console.log("SELECT points FROM users WHERE id = "+id);
con.query("SELECT points FROM users WHERE id = "+id, function (err, result, fields){
if(err) return reject(err);
resolve(result[0].points);
});
});
}
checkPoints(message.author)
.then(function(result) {
message.author.send(result);
});
Upvotes: 2