I am new to Node JS and i want to create a website with expressJS and Node.JS and i want to two create a async query function, to get the result in a variable - so that i can use this function for all queries.
I create a db.js with the following code:
const mysql = require("mysql")
const connection = mysql.createPool({
host: "...",
user: "...",
password: "...",
database: "..."
})
var sql_statement = {...}
function queryResult(function(statement) { //Async function
connection.getConnection(function (error, connection) {
if (error) throw error
connection.query({...}), function (error, results)
connection.release()
return results
})
})
}
var output = queryResult(sql_statement)
console.log(output)
but it doesn't work this in example works and it shows me the result in the console:
//code...
connection.getConnection(function (error, connection) {
if (error) throw error
connection.query({...}), function (error, results)
console.log(results)
connection.release()
})
})
//code...
info: the website is very simple and and i want to use this function to output my SQL data in expressJS on the website like this:
//code...
app.get("/", function (req, res) {
var sql_statement = {...} //SQL stmt for index.html
entries = queryResult(sql_statement)
res.render("index.html", {
title: "Home",
show_entires: entries
}
app.get("/articles", function (req, res) {
var sql_statement = {...} //SQL stmt for articles.html
entries = queryResult(sql_statement)
res.render("article.html", {
title: "Articles",
show_entires: entries
}
//code...