Intent
Establishing a connection with a DB in my route, running a query, capturing the result, and making it accessible to my index view to render in the DOM.
Problem
DB connects and returns results successfully in the console. However, fails to push this result into the "finalResult" array.
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
// Establish Connection with Database
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : 'xxxxxxx',
database : 'my_db'
});
connection.connect();
// // Query and post result to console
connection.query('SELECT * FROM products', function(error, results, fields) {
if (error) throw error;
doSomething(results[0]);
});
connection.end();
var finalResult = ['hello'];
function doSomething(results) {
console.log(results.name);
finalResult.push(results.name);
}
console.log(finalResult);
// Render/make accessible to views
res.render('index', {
pageTitle: 'Home',
result: finalResult
});
});
module.exports = router;
doSomething(results[0]); successfully pushes the result into the doSomething() function because console.log(results.name) returns the correct query result. Issue occurs with finalResult.push(results.name) because console.log(finalResult) only returns an array with "hello" when it should have "hello" plus the query result.