javascript - 在带有辅助函数的 ejs 中使用 .then 返回 [ object promise ]

标签 javascript mysql node.js promise

在我的 ejs 文件中,我在另一个返回 mysql 结果的文件中调用辅助函数。问题是即使我使用 .then(),返回值也是 [object promise]。我不确定为什么。
辅助函数

    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 文件
    <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>

最佳答案

您不能使用 async与 EJS,read this issue .
这样的async方法应该在 nodeJS 后端完成,所以你有类似的东西:

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

关于javascript - 在带有辅助函数的 ejs 中使用 .then 返回 [ object promise ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65026000/

相关文章:

javascript - JS 检测到一个特定 .mp4 文件的错误宽度和高度

mysql - CREATE TEMPORARY TABLE 包含与 SELECT 完全不同的行

php - 如何使用 PHP 和 MySQL 根据列值从表中获取数据

node.js - 尝试在 mocha 中使用 async/await

javascript - 如何延迟基本的 HTML 工具提示?

javascript - 缩放 X 时 Highcharts 为空

javascript - AngularJS 表的性能问题

MYSQL插入concat结果

node.js - 长级别升级查询

node.js - Electron JS写文件权限问题