I use MySQL in EJS for getting data from db(with promises). When I got the data, I console.log(data), and I can see data in server console. BUT when I want to display the data with ejs, nothing happened, why? Here's my code:
<%
let conn = connection() //Connection is a func who returned a mysql.createConnection() with the good props
function GetDataToShow(){
return new Promise((resolve, reject) => { //Promise returned, while promise is not returned, js does not continue to execute the code if function is async and await keyword is used when this function is called
conn.query(
"SELECT * FROM articles",
(err, result) => {
return err ? reject(err) : resolve(result)
}
)
})
}
let results = [];
(async () =>{
conn.connect()
results = await GetDataToShow()
console.log(results) //Data is show in the console(it works)
conn.end()
for (let index = 0; index < results.length; index++) { %>
<h1><%= results[index].name</h1> <!--But not that !!!!!-->
<%}
console.log("Happy coding !")
})()
%>
You can't use asynchronous code in EJS.
Your function goes to sleep when it hits the await, the EJS finishes, the result it sent to the browser, then the function wakes up and does the logging (by which time it is too late to inject content into the data that has already been sent to the browser).
Treat EJS is a view layer, and just as a view layer.
Collect all the data you need before it reaches EJS (typically you would do this in an Express.js route), put it into a sensible data structure, then pass it to the EJS template.
app.get('/path/example', async (req, res) => {
const data = await getDataFromDatabase();
res.render('/pages/example', {databaseData: data});
});