0
I possess a value foo
which is obtained in an asynchronous method in a file db.js
.
The query is being performed normally and I can already capture the variable data foo
in my file index.js
, but while trying to hold a foreach by passing foo
to my file index.ejs
, he 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 don’t think 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
}