Ionică Bizău Ionică Bizău - 5 months ago 30
Javascript Question

How to handle callback responses in Ejs

In my Node.js application I want to call some async function in Ejs code and render the result. I tried:

<ul>
<% setTimeout(function () { %>
<% supplies = [1, 2, 3, 4]; %>
<% for(var i=0; i<supplies.length; i++) {%>
<li><%= supplies[i] %></li>
<% } %>
<% }, 1000) %>
</ul>


But it seems it doesn't work. Why doesn't it work and how I can fix it?

Answer

Ok, so it seems that Ejs doesn't support such a feature, but what we can do is to deasync the function using the deasync module.

<% function foo (timeout, callback) { %>
<%     setTimeout(function () { %>
<%          callback(null, [1, 2, 3, 4]; %>
<%     }, timeout); %>
<% } %>

<% var Deasync = require("deasync") %>
<% var fooSync = Deasync(foo) %>

<ul>
<% supplies = fooSync(1000); %>
<% for(var i=0; i<supplies.length; i++) {%>
<li><%= supplies[i] %></li>
<% } %>
<% }, 1000) %>
</ul>