Here is my code I am doing this in node.js and node-mysql module.
function registerUser(username, password) {
var state = '';
if (!username) { //line #4
state = 'Missing <strong>username</strong>';
return state;
}
if (!password) { //line #8
state = 'Missing <strong>password</strong>';
return state;
}
function addUser() {
statement = 'INSERT INTO data (user_name, user_password) VALUES (\'' + username + '\', \'' + password + '\');';
connection.query(statement, function(err) {
if (err) throw err;
console.log('User ' + username + ' added to database');
})
}
connection.query('SELECT user_name FROM data WHERE user_name=\'' + username + '\'', function(err, result){
if (err) throw err;
if (!result[0]) {
addUser();
console.log('User ' + username + ' added.');
state = 'Success!';
return;
} else {
console.log('User ' + username + ' already exists.');
state = 'User already exists!';
return;
}
})
return state; //line #33
}
Upon triggering if statements on line #4 & #8 state
variable is being assigned and returned as intended. However code executed in anonymous function in connection.query
is not assigning state
and return on line #33 is returning nothing.
I am not sure if there is problem with variable scope or with that connection.query
is non-blocking and return on line #33 is being executed before anonymous function.
Is there any way to make this work and return also state
from anonymous function?
Thank you in advance.