Using .then in ejs with helper function returns [ object promise ]

Viewed 830

In my ejs file, I am calling a helper function in another file that returns a mysql result. The problem is the returned value is [ object promise ] even when I am using .then(). I am unsure why.

helper function

    var conn = require("../routeFunctions/mySqlConn");


//get the amount of likes
var getLikesCountEjs = function(idOfPost) {
    var query = getLikeCount(idOfPost).q;
    var preparedStatement = getLikeCount(idOfPost).ps;
    return new Promise(function (resolve, reject) {
      conn.query(query, preparedStatement, function (err, result, fields) {
         if (err) {
            reject("problem getting likes count");
          } else {
            resolve(result[0].count);
          }
      });
    });
  }

  //get all likes count
  function getLikeCount(idOfPost) {
    var query = "SELECT COUNT(*) as count FROM likes where idOfPost = ?";
    var preparedStatement = [parseInt(idOfPost)];
    return { ps: preparedStatement, q: query };
  }

  //you can return multiple functions 
  module.exports = { getLikesCountEjs : getLikesCountEjs };

ejs file where i am calling the function

    <a href="#" class="link-black text-sm interactSetLikesTimeLine" id = "setLikes-<%=posts.id%>">
    <i class="far fa-thumbs-up mr-1 initalLoadSetLikes"> Likes <%= asyncFunctions.getLikesCountEjs(posts.id).then(function(result){ console.log(result); }) %> </i> 
  </a>
1 Answers

You can't use async with EJS, read this issue.

Such async methods should be done on the nodeJS backend, so you have something like:

app.get('...', async (req, res) => {
  res.render('...', {
    data: await asyncFunctions.getLikesCountEjs(posts.id)
  })
})

Should suffice.

Related