LaVOZs

The World’s Largest Online Community for Developers

'; node.js - Use Async function to print value in ejs view Express js - LavOzs.Com

I passed the model from controller to use it in view, but it seems like printing values using Async functions is not possible in a view. what could be the suitable way to use a model to print inside an async function in a view?

I need to get the userImage from user table. (ps: use of console.log(userImage) in the same place is working, it's driving me crazy. please help me)

        <img src="<% userModel.findById(postData.uid,function(err,user) {%>   <%=user.userImage%>  <% }) %>" class="mx-2"><a href="#" class="mx-2">Anmol D. Pradhan</a>

At first, that's absolutely not the best practice.

You should do something like that:

    // ...
    const userModel = require('/your-path-to/userModel');
    app.get('/your/url', async (req, res) => {
        const user = await userModel.findById(uid);
        res.render('/youpage.html', {
            user: user
        });
    });
<!-- Here's your EJS template -->

<img src="<%= user.userImage %>" class="mx-2"><a href="#" class="mx-2">Anmol D. Pradhan</a>

That's just an example. I don't know how actually your routes structured, but I hope that will help.

Related
What is Node.js' Connect, Express and “middleware”?
How to get the full url in Express?
NodeJS / Express: what is “app.use”?
map function for objects (instead of arrays)
How to access the GET parameters after “?” in Express?
Proper way to return JSON using node or Express
bodyParser is deprecated express 4
Call async/await functions in parallel
Using async/await with a forEach loop
Generating an array in the view and passing it into the controller