I'm new to Node.js and Express. I understand that the functions are executed asynchronously, but I don't get how to use global variables. Here I connect to mysql database, retrieve the query results and render them on my test.html page. Then in the mysql.js file, I want to save those results in an array called entry, so that the other get() can use those same results. The only alternative I can think of with my limited understanding of Node.js is to just query the database again in the other get(). How can I use this global to save my query results from the anonymous function? Also what event and function do I call so that I can execute my connection.end() correctly?
//mysql.js
var express = require('./express');
var mysql = require('mysql');
var hbs = require('./hbs');
var app = express();
app.set('view engine', 'html');
app.engine('html', hbs.__express);
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
database: 'db',
port: 3306
});
connection.connect();
entry=[];
app.get('/', function(req, res){
connection.query(
'SELECT * FROM table where ID < 10;',
function(err, result, fields)
{
if(err) throw err;
res.render('test',{title:"title", entries:result});
entry = result;
});
});
app.get('/article/:id', function(req, res) {
res.render('article',{title:entry.title, blog:entry});
});
app.listen(3000);
//connection.end();
<h1>HTML Test</h1>
{{#each entries}}
<p>
<a href="/article/{{ID}}">{{Name}}</a><br/>
Name: {{Name}}
</p>
{{/each}}