Reputation: 671
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.
Upvotes: 0
Views: 43
Reputation: 504
Please note when you query database from mysql module is synchronous (the query takes function as argument -- callback). That's mean you cannot take result value as variable outside the query function. Try to use async/await or promise to get returned value.
Upvotes: 1
Reputation: 3
Try to write console.log(finalResult) inside doSomething function, after you pushed the new data to finalResult array.
I think that you see only "helo" because console.log(finalResult) execute before the doSomething function finished (before you add the data to finalResult array).
Upvotes: 0