I have a foo
value that is obtained in an asynchronous method in a db.js
file.
The query is being performed normally and I can already capture the data of the foo
variable in my index.js
file, but when trying to perform a forEach passing foo
to my index.ejs
file, it informs that foo is not defined
index.js
const express = require('express');
const app = express();
const db = require('./db/db.js');
db.getData().then(function (result) {
runServer(result);
}).catch(function (error) {
console.log(error);
});
function runServer(foo) {
app.set('view engine', 'ejs');
// index page
app.get('/', function(req, res) {
res.render('pages/index', foo);
});
app.listen(8080);
}
index.ejs
...
<ul>
<% foo.forEach(function(element) { %>
<li><%= element.id %> - <%= element.nome %></li>
<% }); %>
</ul>
...
db.js (I can not believe the problem is here)
const sql = require("mssql")
const s = "SELECT ..."
const c = {
user: "...",
password: "...",
server: "...",
database: "..."
}
function execQuery(config, sqlQuery) {
return new Promise(function (resolve, reject) {
const conn = new sql.ConnectionPool(config)
const req = new sql.Request(conn)
conn.connect(function (err) {
if (err) {
console.log(err)
return
}
req.query(sqlQuery, function (err, recordset) {
if (err) {
console.log(err)
} else {
resolve(recordset.recordset)
}
conn.close()
})
})
})
}
module.exports.getData = async function() {
let data = await execQuery(c, s)
return data
}