这是我的函数返回计数正常。但我想在我的回复中使用它的值。
var PostComment = require("../models/PostComment");
var getPostCount = function (postId,res) {
return PostComment.findAll({where: {post_id: postId}}).then(function (comments) {
return comments.length;
});
}
module.exports = {
getPostCount: getPostCount
}
这是我的另一个功能。控制台日志工作正常。但我需要回报价值。
arr.push({
id: item.id,
post_userid: item.post_userid,
post_sendername: item.post_sendername,
post_description: item.post_description,
attach_status: item.attach_status,
post_datetime: item.post_datetime,
post_status: item.post_status,
remove_id: item.remove_id,
attachment_list: item.tbl_post_attachments,
total_like:totalLikes,
comment_count:Samparq.getPostCount(item.id, res).then(function (commentCount) {
console.log(commentCount);
}),
comment_list:item.tbl_post_comments
});
答案 0 :(得分:0)
旁注:
您可以在第一个代码块中使用count
方法:
var PostComment = require("../models/PostComment");
var getPostCount = function (postId) {
return PostComment.count({where: {post_id: postId}});
}
module.exports = {
getPostCount: getPostCount
}
在您的第二个代码块中,您在Promise
中获得了comment_count
,而不是实际的数字。
您需要先获取计数,然后将其添加到对象中。
Samparq.getPostCount(item.id).then(function (count) {
arr.push({
id: item.id,
post_userid: item.post_userid,
post_sendername: item.post_sendername,
post_description: item.post_description,
attach_status: item.attach_status,
post_datetime: item.post_datetime,
post_status: item.post_status,
remove_id: item.remove_id,
attachment_list: item.tbl_post_attachments,
total_like:totalLikes,
comment_count: count,
comment_list:item.tbl_post_comments
});
})
SIDENOTE#2: 如果您使用async await(这是节点的新功能),您将能够使其看起来更像您的原始代码。 如果你在异步函数中,那么你的第二个代码块可能如下所示:
arr.push({
id: item.id,
post_userid: item.post_userid,
post_sendername: item.post_sendername,
post_description: item.post_description,
attach_status: item.attach_status,
post_datetime: item.post_datetime,
post_status: item.post_status,
remove_id: item.remove_id,
attachment_list: item.tbl_post_attachments,
total_like:totalLikes,
comment_count: await Samparq.getPostCount(item.id),
comment_list:item.tbl_post_comments
});