NodeJS - 执行 4 次连续收集计数的水线最佳方法

NodeJS - waterline best way to do 4 consecutive collections counts

本文关键字:方法 最佳 执行 连续 NodeJS      更新时间:2023-09-26

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

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

   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 个计数的情况下做到这一点?

您可以利用像异步这样的模块以更易读的方式执行您想要的事情。 默认情况下,该模块由 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);
    }
);