我正在尝试获取不同值和项目数量的列表。像这样:
sheet_kinds: [
"cars" (10 items),
"computers" (23 items),
"utilities" (88 items)
],
因此获取不同值的查询是可以的。我的代码:
getValues:function(next){
Sheet.find().distinct('kind', function(err, rs){
for (var i = 0; i < rs.length; i++) {
Sheet.count({kind:rs[i]}, function(err, c){
next(null, rs); <====== THIS IS NOT GOOD
});
};
});
}
我知道我不能在循环内运行 next() 。但是我怎样才能获得计数值的完整列表并仅在所有项目返回后才运行 next() ?
最佳答案
在这种情况下,您最好使用 async
安装
npm install --save async
需要
var async = require('async');
使用
getValues:function(next){
Sheet.find().distinct('kind', function(err, rs){
async.map(rs, function (item, done) {
Sheet.count({kind:item}, done);
}, next);
});
}
详情
getValues:function(next){
Sheet.find().distinct('kind', function(err, rs){
// async.map is used to map a collection asynchronously
// the cb will be invoked once for each item in rs
async.map(rs, function (item, done) {
// the done callback needs to be invoked exactly once
// in this case, we just pass it to count, since
// the (err, count) result is exactly what we want (getting us the count)
Sheet.count({kind:item}, done);
// next is invoked with the err, if any, and
// the resulting map (an array of counts)
}, next);
});
}
更新
解决评论中的问题
getValues:function(next){
Sheet.find().distinct('kind', function(err, rs){
async.map(rs, function (item, done) {
Sheet.count({kind:item}, function (err, count) {
done(err, {kind:item,count:count});
});
}, next);
});
}
关于node.js - 查询循环中的回调 hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20079166/