[英]Sequelize nodejs pass value to another function
這是我的返回計數很好的函數,但是我想在響應中使用它的值。
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
});
旁白:您可以在第一個代碼塊中使用count
方法:
var PostComment = require("../models/PostComment");
var getPostCount = function (postId) {
return PostComment.count({where: {post_id: postId}});
}
module.exports = {
getPostCount: getPostCount
}
在第二個代碼塊中,您將在comment_count
獲得一個Promise
,而不是一個實際數字。
您需要首先獲取計數,然后將其添加到對象中。
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
});
})
觀點2:如果您使用的是async await(這是Node的新功能),則可以使其看起來更像原始代碼。 如果您在異步函數中,則您的第二個代碼塊可能如下所示:
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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.