node.js - 查询循环中的回调 hell

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

最佳答案

在这种情况下,您最好使用 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/

相关文章:

javascript - 模式验证函数在 Mongoose 中如何工作?

javascript - 将 JSON 中的键小写 - Node JS

node.js - Mongoose: ref 自定义字段名称

node.js - 如何从 Socket.IO 向数组 (MongoDB) 添加数据? (node.js)

javascript - 如何在超时后杀死 spawnSync

node.js - 在 mongo/mongoose 中一次连接到多个数据库

node.js - 由于空数组包含电子邮件为空的文档,MongoDB错误E11000重复键错误集合

sql - 如何为 Sequelize 转换 SQL 查询?

javascript - SQL SELECT 和 UPDATE 语法

arrays - NodeJS : Array. 减少以查找对象数组中的最小值和最大值