NodeJS getting and passing variables

Problem

I am having some trouble figuring out variables "passing" (I know it's not the right term, I'll explain), given the asynchronous nature of node.js.

Please have a look at the following:

connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if(err) {
    throw err;
  }
  var solution = rows[0].solution;
});

res.render('index', { title: solution });

As you can imagine, I am getting a reference error, solution is not defined. This is because the res.render is done before getting the solution from the mysql server.

How can I make it render the page once the solution is defined? I know it's something really little and stupid and is really at the very core of node, but please help me understand.

Problem courtesy of: user1130217

Solution

The second parameter of the connection.query is your callback which gets run after the database returns. Why not put the res.render line inside the callback? That way the render function isn't called until you have your data ready.

connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if(err) throw err;
  var solution = rows[0].solution;
  res.render('index', { title: solution });
});

Callbacks can be a little tricky when you're first getting started with Node. You just have to think out the steps that need to happen and which are async. From there you just need to make sure your callbacks allow the process to continue.

Solution courtesy of: Joe Doyle

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.