IHazza IHazza - 21 days ago 11
Javascript Question

NodeJS/Javascript function returning undefined

I'm writing a basic web app in Node, Express and MySQL. Its just a basic site, where a user can create an account, view other peoples accounts, and post infomation on their profile, and I'm creating it to learn Node and javascript.
So, I'm up to creating the userlist, and I've created a nice function that returns all the users in the database. Here is the code:

function getAllUsers() {
var query = " \
SELECT \
id, username, email, password \
FROM \
users \
";
connection.query(query, function(err, rows) {
if (err) throw err;
return rows;
});
}


Now, I'm using this function here:

router.get('/list', function(req, res) {
var users;
users = getAllUsers();
res.render('user/list', {'title': 'Users', 'users': users});
});


But users is undefined. Why is this?

I'm pretty sure the MySQL connection is working properly, but here is how I connect it, just in case it comes in handy:

var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'firstnodeapp'
});

connection.connect();


Thanks

--- EDIT ---
I thought I should also mention, rows is defined in the getAllUsers() function, but once I return it it is no longer defined.

Answer

Callbacks to the rescue (the most simple answer)

Your query is executing asynchronous, that means, when the function ends the query is still executing and your "users" variable ends being undefined.

Just do this:

function getAllUsers(callback) {
    var query = " \
    SELECT \
      id, username, email, password \
    FROM \
      users \
    ";
    connection.query(query, callback);
}

router.get('/list', function(req, res) {
    getAllUsers(function(err, rows) {
          // Or better yet, respond with the correct html code
          if (err) throw err;

          res.render('user/list', {'title': 'Users', 'users': rows});
    });
});

It should work pretty well. Study about Callbacks/Promises/Observables