ejs async与node Express同步为true [英] ejs async true with node Express
本文介绍了ejs async与node Express同步为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想调用一些异步函数,这些函数可以从我的ejs文件中调用.
I want to call some of my functions which are asynchronous to be called from within my ejs files.
就像我将此功能设置为我的 app.locals.someFunction
Like I have this functions set as my app.locals.someFunction
async someFunction(param){
let data = await someAsyncStuff();
// & other things
return data;
}
,我想在ejs文件中使用它,如下所示:
and I want to use it inside ejs file as below:
<%
let data = await someFunction()
for(let x of data){%>
<li><%=x%></li>
<%}%>
如果通过 {async:true}
作为选项传递,则ejs可以实现.但是,当我的视图引擎设置如下所示时,该在哪儿传递呢?
This is possible with ejs if {async:true}
is passed as an option. But where exactly should I pass this when my view engine setup is like the following?
//view engine setup
app.engine ('.html', ejs.renderFile);
app.set ('view engine', 'html');
推荐答案
而不是res.render()
instead res.render()
const ejs = require('ejs');
const html = await ejs.renderFile(view, data, {async: true});
res.send(html);
每个包含等待的内容
<body>
<%- await include(pageView);%>
</body>
现在异步很好
<%
let data = await collection.find().toArray();
for(let x of data){%>
<li><%=x%></li>
<%}%>
这篇关于ejs async与node Express同步为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文