I'm create a Node js application where I need to get some data from database and pass it to EJS file for rendering. To make this possible I created a JSON object in the GET app.get("get", (req, res){
block, however everything works fine in the query block where I copied the result into the JSON object to use it for rendering until I get out of the query block, the whole JSON object goes empty to the initial state? I don't know why is it happening.
Here's the code:
app.get("/result", (req, res)=>{
loadDefaultValues(req);
let sess = req.session;
let result = {
requests: undefined
};
if(sess.session_id){
pool.getConnection((err, con) => {
if (err) throw err;
con.query(`SELECT * FROM requests`, function (err, newrequests, fields) {
con.release();
if(err) throw err; // remove on build
console.log("1"); // logs before updating value
console.log(result); // logs before updating value
result.requests = newrequests;
console.log("2"); // logs after updating value
console.log(result); // logs after updating value
});
});
console.log("3");
console.log(result);
// return res.render("avail_requests", result);
}
return res.render("dashboard");
});
Here in the 1st & 3rd console.log
gives the same output eventhough 3rd one still would be able to access the result object.
Here's the output:
3
{ requests: undefined }
1
{ requests: undefined }
2
{
requests: \[
RowDataPacket {
request_id: 1,
name: 'First',
email: '1@gmail.com'
},
RowDataPacket {
request_id: 2,
name: 'Second',
email: '2@gmail.com'
}
\]
}