Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda