用于检索论坛作者列表的Sailjs代码效率低下

Sailjs code to retrieve list of author for forum ineffecient

本文关键字:代码 Sailjs 效率 列表 检索 论坛 用于      更新时间:2023-09-26

我正在使用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 installrequire async和Lodash库才能使上述工作(尽管如果您愿意,您可以重写它以不使用Lodash)。此外,您几乎不需要在您的Sails控制器中使用(甚至声明)next。控制器应该是中间件链的最后一站,除非在极少数情况下,如果您发现自己想要使用next,那么您可能可以使用策略来解决问题。