Display dynamically an image using express and EJS

前端 未结 1 1853
日久生厌
日久生厌 2021-01-27 18:21

I have a collection containing different URLs of images. I retrieve the URL I want and want to pass it to the jade template like:

app.get(\'/\',function(req,res)         


        
1条回答
  •  清歌不尽
    2021-01-27 19:16

    From what I've gathered in your code:

    app.get('/',function(req,res){
        mongoDB.getUsedHomePageOne(function(err, result){
            if(!err){
                console.log("getUsedHomePageOne : ");
                console.log(result);
                app.locals['homePageImg'] = result.url;
                app.render('userPageEjs.html',function(err,renderedData){
                   console.log(renderedData);
                   res.send(renderedData);
                });
            }
        });
    });
    

    Basically, you have an async function to the DB and you quickly render the template before waiting for the DB function to complete. The normal pattern when using async functions whose results should be used down the line, you have to call the next function inside the async function. However, this might lead to callback hell (similar to how I've written the fix above), so an alternative like Promises or async.js is usually preferred.

    0 讨论(0)
提交回复
热议问题