Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda