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 に答える