NodeJS - 执行 4 次连续收集计数的水线最佳方法
NodeJS - waterline best way to do 4 consecutive collections counts
我想创建一个仪表板,在其中显示简单的统计信息,如用户计数、评论计数等。
我正在使用类似的东西来计算我的收藏
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);
}
);
相关文章:
- 有条件更新d3.js力图中节点的最佳方法
- 将jQuery.ech()方法转换为本地JavaScript抽象的最佳方法是什么
- 处理浮点错误的最佳方法是什么
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- 从数组中删除元素的最佳方法是:javascript/jquery
- 以编程方式填充组合框道场 (1.8) 的最佳方法是什么?
- 列出没有 mysql 的元素的最佳方法是什么
- 在jquery库中重新定义方法的最佳方法
- Javascript,用vars创建对象的最佳方法
- 使用 jQuery 从 HTML 中获取某些值的最佳方法
- 在变量中保存值的最佳方法是在应用程序关闭后使用,然后使用apachecordova在android中重新启动
- 在d3.json中使用d3.csv组合多个csv文件数据输入的最佳方法是什么
- 用jasmine测试JavaScriptUI的最佳方法
- 使用javascript:在没有阻止html标记(<b>、<p>等)的情况下,阻止脚本的最佳方法
- 如果我返回表,检查 Ajax 调用是否为 200 OK的最佳方法是什么
- JavaScript - 创建可链接函数时的最佳方法是什么
- 在上下文菜单项单击上显示侧边栏/弹出窗口的最佳方法是什么
- 在 JavaScript 中获取范围的随机数的最佳方法
- 在对象类上实现 jquery 作用域的最佳方法
- 将同步函数包装到承诺中的最佳方法是什么?