I'm writing a basic user creation system in Node.js and I want to find out what the results of the createUser function are. The code itself works fine, with new users being posted, and already existing users being stopped. I would like to show this to the end user, so I setup a variable to return a numeric value representing what the outcome was.
The problem is, the value is never assigned to. The final console log always reads undefined, even though my other log statements appear. I feel like this is more of a JavaScript syntax question, but I am stumped.
User.prototype.createUser = function () {
console.log('Begin createUser...');
var email = this.email;
var wasUserCreated; <------- variable to assign
pg.connect(process.env.DATABASE_URL, function (err, client) {
if (err) {
console.log(err.message, err.stack);
wasUserCreated = 0; <------assigning to variable?
}
else {
var query = client.query('SELECT email FROM users WHERE email=$1', [email],
function (err, results) {
if (results.rows.length > 0) {
console.log('That email address has already been registered!');
wasUserCreated = 1; <------assigning to variable?
}
else {
console.log('Email address not found, inserting new account');
insertNewUser();
wasUserCreated = 2; <------assigning to variable?
}
});
}
});
console.log("wasUserCreated: " + wasUserCreated); <------always reads 'undefined'
return wasUserCreated;
};