Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ejs async true with node Express

I want to call some of my functions which are asynchronous to be called from within my ejs files.

Like I have this functions set as my app.locals.someFunction

async someFunction(param){
  let data = await someAsyncStuff();
  // &  other things
  return data;
}

and I want to use it inside ejs file as below:

<%
let data = await someFunction()
for(let x of data){%>

   <li><%=x%></li>

<%}%>

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');

like image 609
Imtiaz Chowdhury Avatar asked Jun 06 '26 07:06

Imtiaz Chowdhury


1 Answers

instead res.render()

const ejs = require('ejs');
const html = await ejs.renderFile(view, data, {async: true});
res.send(html);

every include with await

<body>
    <%- await include(pageView);%>
</body>

async now fine

<%
let data = await collection.find().toArray();

for(let x of data){%>

   <li><%=x%></li>

<%}%>
like image 185
Nikolai Savun Avatar answered Jun 08 '26 00:06

Nikolai Savun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!