I'm new in nodejs and expressjs I want to do some query on my database table and show the result in view but i cant do it:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "imanweb"
});
/* GET home page. */
router.get('/', function(req, res, next) {
let objects=['a','b']
con.connect(function(err){
if(err) throw err;
con.query("select * from tags", function (err, result) {
if (err) throw err;
result.forEach(function(element) {
objects.push(element);
console.log("Result: " + element.title);
}, this);
});
})
console.log("Array: " + objects);
res.render('index', { title: 'Express' ,objs:objects});
});
module.exports = router;
actually the log of this code is like this:
Arr:a,b
Get 200 /410.25 ms --196
Result:php
Result:.net
so it seems the last line of my code is running sooner as the past lines(query)!
it's some thing like asynchronous code running!. so when i give objects to objs parameter. there is no query result inside that.
as solution I tried to use then() but i got > undefined then error in my code..
How can I handle that ??