在循环查询中回调地狱

时间:2013-11-19 18:25:12

标签: node.js mongoose

我正在尝试获取不同值和项目数的列表。像这样:

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()?

1 个答案:

答案 0 :(得分:2)

在这种情况下,使用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);
    });
}