查询循环中的callback地狱
我试图得到不同的值和项目数清单。 喜欢这个:
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()只有在所有的项目后?
在这种情况下,使用asynchronous会更好
安装
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); }); }