Abbas
Abbas

Reputation: 1255

.forEach() not printing anything in 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

Upvotes: 0

Views: 349

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

Your asynchronous calls won't complete until after the template has already been rendered. You need to get that data together before you render the template, e.g.:

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...
    });

...or similar.

Upvotes: 1

Related Questions