如何在async eachSeries for Node中正确获取结果数组?

时间:2015-06-06 15:32:31

标签: node.js mongodb node-async

我尝试使用异步eachSeries来编码每个类别的报告计数。类别和报告存储在单独的集合中,然后我首先获得可用的类别并对它们执行计数搜索。

这是我的代码:

    Category.find({},{_id:0, name: 1}, function (err, foundCategories) {
        async.eachSeries(foundCategories,
            function (item,callback) {
                Report.count({category: item.name}, function (err,count) {
                    var name = item.name;
                    console.log(count);
                   return callback(null,{name: count});
                });
            }
        ,function (err, results) {

            if (err)
                response.send(err);
            response.send(JSON.stringify(results));
        });
    });

问题在于我没有收到任何内容,console.log输出实际数字,我做错了什么?

2 个答案:

答案 0 :(得分:3)

eachSeries的API不会向最终回调提供任何结果 - 只有失败案例中的错误。在成功的情况下,它只是一个纯粹的控制流“eachSeries is done”指标,但是没有提供从worker函数传递值的机制。 mapSeries确实提供了您需要的功能。

答案 1 :(得分:1)

与Peter的回答类似,async.waterfall为您提供函数的瀑布执行,同时将返回值传递给瀑布链中的下一个异步函数。