【问题标题】:MySQL data is returned(promises is used) but EJS doesn't display the result in HTML page返回 MySQL 数据(使用 Promise)但 EJS 不在 HTML 页面中显示结果
【发布时间】:2022-01-26 06:38:21
【问题描述】:

我在 EJS 中使用 MySQL 从数据库中获取数据(带有承诺)。当我得到数据时,我控制台.log(数据),我可以在服务器控制台中看到数据。但是当我想用 ejs 显示数据时,什么也没发生,为什么?这是我的代码:

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


})()
%>

【问题讨论】:

  • 来自“console.log(results)”的打印在哪里?
  • 我已经编辑了我的问题以获得更多理解

标签: javascript mysql node.js ejs


【解决方案1】:

您不能在 EJS 中使用异步代码。

您的函数在遇到await 时进入睡眠状态,EJS 完成,将结果发送到浏览器,然后函数唤醒并进行日志记录(此时将内容注入已经发送到浏览器的数据)。


把EJS当作一个视图层,而只是作为一个视图层。

在到达 EJS 之前收集您需要的所有数据(通常您会在 Express.js 路由中执行此操作),将其放入合理的数据结构中,然后将其传递给 EJS 模板。

app.get('/path/example', async (req, res) => {
    const data = await getDataFromDatabase();
    res.render('/pages/example', {databaseData: data});
});

【讨论】:

    猜你喜欢
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    相关资源
    最近更新 更多