Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
MySQL data is returned(promises is used) but EJS doesn't display the result in HTML page

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 !") 


})()
%>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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});
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!