Pergunta

I want to create a dashboard where I'll be showing simple stats like count of users, count of comments etc.

I am counting my collections using something like

   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(...)    
       })

   })

which is a bit ugly I think. Is there any other way to do it without nesting 4 counts?

Foi útil?

Solução

You can take advantage of a module like async to do you want in a more readable way. The module is globalized by Sails by default, meaning it's available in all of your custom code. Using async.auto, you would rewrite the above as:

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);

    }
);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top