MySQL 返回了数据(使用了 promises)但是 EJS 没有在 HTML 页面中显示结果
MySQL data is returned(promises is used) but EJS doesn't display the result in HTML page
我在 EJS 中使用 MySQL 从 db 获取数据(有承诺)。当我得到数据时,我 console.log(data),我可以在服务器控制台中看到数据。但是当我想用 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 !")
})()
%>
您不能在 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});
});
我在 EJS 中使用 MySQL 从 db 获取数据(有承诺)。当我得到数据时,我 console.log(data),我可以在服务器控制台中看到数据。但是当我想用 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 !")
})()
%>
您不能在 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});
});