.forEach() not printing anything in EJS

时间:2018-10-02 09:14:22

标签: javascript node.js express ejs

Have this .ejs file that loops through an object and fetches some data from an API. After the data is fetched it just does nothing.

I console logged the API results and they are alright, but the problem is that it is not echoing them to the screen.

Here's the code:

<div class="bg-white jumbotron no-shadow">
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-sm-12">
                <%
                    if(apiResults.featured.male){
                        %>
                            <div class="row">
                                <%
                                Array.from(apiResults.featured.male).forEach((profile) => {
                                helper.api.getPhotoByKey(profile.photoKey)
                                    .then(photoURL => {
                                        %>
                                            <div class="col-xs-4">
                                                <img src="<%= photoURL%>">
                                            </div>
                                        <%
                                    })
                                    .catch(err => console.log(err))
                                })%>
                            </div>
                        <%
                    }
                %>  
            </div>
        </div>
    </div>
</div>

I am very new to EJS and NodeJS, can anybody guide me through this? Thank You

1 个答案:

答案 0 :(得分:1)

您的异步调用要等到模板被渲染后才能完成。您需要在渲染模板之前 将这些数据汇总在一起,例如:

Promise.all(
    Array.from(apiResults.featured.male)
    .map((profile) => helper.api.getPhotoByKey(profile.photoKey))
    )
    .then(photoURLs => {
        // Add them to your data and call ejs.render...
    });

...或类似的