Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在ejs中使用.then和helper函数返回[object promise]_Javascript_Mysql_Node.js_Promise - Fatal编程技术网

Javascript 在ejs中使用.then和helper函数返回[object promise]

Javascript 在ejs中使用.then和helper函数返回[object promise],javascript,mysql,node.js,promise,Javascript,Mysql,Node.js,Promise,在我的ejs文件中,我正在调用另一个文件中的helper函数,该函数返回一个mysql结果。问题是,即使在使用.then()时,返回的值也是[object promise]。我不知道为什么 辅助函数 var conn = require("../routeFunctions/mySqlConn"); //get the amount of likes var getLikesCountEjs = function(idOfPost) { var query

在我的ejs文件中,我正在调用另一个文件中的helper函数,该函数返回一个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一起使用

这样的
async
方法应该在nodeJS后端完成,因此您可以使用以下方法:

app.get(“…”,异步(req,res)=>{
res.render(“…”{
数据:wait asyncFunctions.getLikeCountEjs(posts.id)
})
})

应该足够了。

您应该在nodeJS后端执行此操作。可以看出,使用您传递的数据呈现EJS文件是不可能的(在我看来也是不实际的)。当然,他们不能渲染将来会发生的事情。他们无法呈现
.then()
中的内容,原因很简单,因为它尚未发生。我可以将其添加到我的助手函数中吗?你是什么意思?只需执行你的helper函数,就像我大致拥有的一样。我对NodeJS和async之类的东西非常陌生,所以我对它有点麻烦。我不确定我是否正确,但是。当我看到app.get时,我想到了我的路线。所以我想。。根据路由请求,使用ejs中加载的my helper函数和“wait关键字”呈现页面。然后在我的ejs中,引用数据而不是实际的helper函数。这将允许我在ejs中使用wait而不会出错。对吗?对不起,我误解了。我想我现在明白了是的,你似乎明白我想说什么了!(使用通过render传递的变量,而不是调用函数)