0

我想创建一个仪表板,我将在其中显示简单的统计信息,例如用户数、评论数等。

我正在使用类似的东西来计算我的收藏

   User.count(function(err, num){
       if (err)
           userCount=-1;
       else
           userCount = num;

       Comment.count(function(err, num){
           if (err)
               commentCount=-1;
           else
               commentCount = num;
           SomethingElse.count(...)    
       })

   })

我认为这有点难看。有没有其他方法可以在不嵌套 4 个计数的情况下做到这一点?

4

1 回答 1

2

您可以利用async之类的模块以更易读的方式来做您想做的事。默认情况下,该模块由 Sails 全球化,这意味着它在您的所有自定义代码中都可用。使用async.auto,您可以将上面的内容重写为:

async.auto({

    user: function(cb) {User.count.exec(cb);},
    comment: function(cb) {Comment.count.exec(cb);},
    somethingElse: function(cb) {SomethingElse.count.exec(cb);},
    anotherThing: function(cb) {AnotherThing.count.exec(cb);}

}, 
    // The above 4 methods will run in parallel, and if any encounters an error
    // it will short-circuit to the function below.  Otherwise the function
    // below will run when all 4 are finished, with "results" containing the
    // data that was sent to each of their callbacks.
    function(err, results) {

        if (err) {return res.serverError(err);}

        // results.user contains the user count, results.comment contains
        // comments count, etc.
        return res.json(results);

    }
);
于 2014-04-07T04:48:44.897 回答