I want to check if a sqlite query got executed properly or not with node.js to check if the name inputed by the user is already in use.
To do so my first assumption was to simply check the returned value of my query (0
if the username is already present in the table or 1
if not ).
/*some code*/
db.serialize (function () {
exports.run = function(query, message) {
db.run(query, function(err) {
if (err) {
console.error(err.message, );
return 0;
}
else{
console.log(message,": ", this.changes, "\n");
return 1;
}
});
}
});
/*some code*/
But the problem is that no matter what the it returns undefined
and thus triggering the wrong behaviour. I also tried to check if my query threw an error but get the same result.
/*some code*/
io.sockets.on('connection', function (socket) {
socket.on('send', function (data) {
if (data.type === 'notice') { //update the hasmap with the name
connectedSockets[socket.id] = data.nick;
var tmp = db.run(`insert into user(username, socket_id, member_of)
VALUES ("${data.nick}","${socket.id}",'default');`
, 'User added to the DB..' + " " + data.nick
+ " " + socket.id + " " + 'default');
if (tmp === 1) {
console.log(connectedSockets, "\n")
io.sockets.emit('message', data);
}
else {
data['invalid_name'] = true;
console.log(data.invalid_name, "TEST invalid_name");
socket.emit('message', data);
}
}
/*some code*/
My second attempt:
/*some code*/
io.sockets.on('connection', function (socket) {
socket.on('send', function (data) {
if (data.type === 'notice') { //update the hasmap with the name
try{
console.trace( db.run(`insert into user(username, socket_id, member_of)
VALUES ("${data.nick}","${socket.id}",'default');`
,'User added to the DB..'+" "+data.nick
+ " "+socket.id+" "+'default'));
console.log(connectedSockets, "\n")
io.sockets.emit('message', data);
}
catch (e) {
data['invalid_name'] = true;
console.log(data.invalid_name, "TEST invalid_name");
socket.emit('message', data);
}
}
/*some code*/
I'm probably missing something quite obvious. Any idea? Thanks
Edit: it was marked as a duplicate of this post How do I return the response from an asynchronous call? but this post is not beginner and friendly and does not specifically explain how answer to my problem. Ajax and XMLHttpRequest are not related to my problem.