0

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;
};
Joseph Idziorek
  • 4,853
  • 6
  • 23
  • 37
Lee Harrison
  • 2,306
  • 21
  • 32

2 Answers2

0

This is due to your query being asynchronous - what your createUser method should do is take a callback as an argument, and invoke cb(err, wasUserCreated, user) or something inside the callback to your query.

Your console.log is always undef because it fires synchronously

some basics in mixu's node book

Alex T
  • 1,232
  • 10
  • 10
0

the 2nd argument of pg.connect is a callback function, which runs asynchronously... so the function returns before the wasUserCreated is modified

David J
  • 659
  • 1
  • 9
  • 25