用于检索论坛作者列表的Sailjs代码效率低下
Sailjs code to retrieve list of author for forum ineffecient
我正在使用SailsJs写一个讨论板,我有一个topic
,其中有一个问题和一堆答复。现在回复是由不同的用户,replyObject
只包含authorId
。我还需要为每个回复显示authorName
。使用我有限的理解,我写了以下控制器:
'showTopic': function(req, res, next) {
if(req.param('id')!=null) {
Topic.findOne(req.param('id'), function foundTopic(err, topic) {
Reply.find({
topicId: topic.id
}).done(function(err, replies) {
if (err) return next(err);
if (!replies) return next();
var authorIds = [];
var authorList = [];
for(var reply =0; reply<replies.length; reply++) {
var authorId = replies[reply].authorId;
if(authorIds.indexOf(authorId) === -1) {
authorIds.push(authorId);
User.findOne(authorId , function foundUser(err, author) {
if (err) return next(err);
authorList.push(author);
});
}
};
res.view({
topic: topic,
replies: replies,
authors: authorList
});
});
}
这段代码也开始看起来像一个深度嵌套的函数,但我不确定如何使用eventproxy来使它更干净。
我从来没有使用过EventProxy,但是在给它一个快速的看之后,我不认为它是你在这里需要的,因为它是有关(不出所料)事件,你正在寻找简化嵌套的异步回调,不是基于事件。我建议使用async库,它可以让您将上面的代码重写为:
'showTopic': function(req, res) {
if (req.param('id') == null) {
return res.send("No topic ID sent!");
}
var authorList = [];
async.auto({
// Find the topic, and send it as an argument to the callback
topic: function(cb) {Topic.findOne(req.param('id')).exec(cb);},
// Find the replies, in parallel to the above
replies: function(cb) {Reply.find({topic: req.param('id')}).exec(cb);},
// After "replies" is done, construct the author list
authors: ['replies', function(cb, results) {
// async.auto stores the results of everything that ran before
var replies = results.replies;
// Get the unique list of authors using Lodash (you could write
// this manually if you don't want to include the Lodash library!)
var authorIds = _.unique(_.pluck(replies, 'authorId'));
// Find all the authors with those IDs
User.find({id: authorIds}).exec(cb);
}]
},
// The second argument to async.auto is called when all of the
// tasks complete, or if any of the callbacks returns an error
function finished (err, results) {
if (err) {return res.serverError(err);}
res.view({
topic: results.topic,
replies: results.replies,
authors: results.authors
});
}
);
}
参见文档中的async。自动查看更多信息。
注释:您需要npm install
和require
async和Lodash库才能使上述工作(尽管如果您愿意,您可以重写它以不使用Lodash)。此外,您几乎不需要在您的Sails控制器中使用(甚至声明)next
。控制器应该是中间件链的最后一站,除非在极少数情况下,如果您发现自己想要使用next
,那么您可能可以使用策略来解决问题。
相关文章:
- 从桌面读取python文件时高亮显示代码
- 如何将函数包装在函数中以避免代码重复
- 通过单击表单中的按钮,在代码生成中使用javascript生成字母数字代码
- 货币代码为欧元-金额的格式不应包含小数
- Regex代码只允许一个空格
- 如何将屏幕分辨率乘以 80%,然后在代码中使用
- 从var向代码隐藏函数传递值
- 如何动态插入jquery代码
- 如何在php变量中嵌入JQuery代码
- 代码不会验证
- 如何从rails中的代码中删除新行( )
- Angularjs代码未在匿名函数中运行
- 如何做到这一点,使代码在不传递条件后执行函数
- 如何在读取XLS/XLSX本地文件时,使用IE的javascript代码启用未标记为安全的ActiveX控件
- 面向对象的Javascript代码在IE7中不起作用
- 将 jQuery 代码添加到 Index.aspx 页面
- 为什么忽略了eval()代码中的语法错误
- 元素在我的代码中不会.fadeTo.Don'I don’我不知道;s错误的JavaScript、JQuery、H
- 如何轻松地将服务器端变量从Java代码转移到客户端代码
- 用于检索论坛作者列表的Sailjs代码效率低下