【问题标题】:Node.js : control flow with forEachNode.js:使用 forEach 控制流
【发布时间】:2014-03-17 00:39:48
【问题描述】:

我正在尝试从数据库对象创建数组:

我有实体“组”,其中有许多“设备”,我想创建所有组的数组,并为每个组创建他的设备列表:

[
{
    "group_id": “1”,
    "name": “My_group”,
    "devices_list": [1, 2, 18]
},
{
    "group_id": “2”,
    "name": “My_second_group”,
    "devices_list": [3, 24]
}
]

我尝试了几种这样的方法:

Group.all(function (err, groups) {
     var resJson = {};
     groups.forEach(function(group, index){
         group.devices(function(err, devices){
            resJson[index] = group;
            console.log(devices);
            resJson[index].devices_list = devices;

            //End of the loop
            if (index == groups.length -1){
                 send({code: 200, data: resJson});
            }
        });
    });
 });

编辑 1:

我也试过这种方法:

var resJson = {};
groups.forEach(function(group, index){
    group.devices(function(err, devices){
        resJson[index] = group;
        resJson[index].devices_list = [];

        devices.forEach(function(device,index2){
            resJson[index].devices_list.push(device);
        });


        //End of the loop
        if (index == groups.length -1){
            send({code: 200, data: resJson});
        }
    });
});

但最后,我的 resJson 只包含空组(没有关联设备的组),其他组不可见。因此,我的 devices_list 都是空的,而 console.log(devices) 显示设备。

看来“发送”指令是在处理非空组之前处理的。

这样做的正确方法是什么?

感谢您的宝贵时间

【问题讨论】:

  • 不应该是怎么回事,但我很好奇它是否是resJson[index].devices_list = devices; 行 - 您是否尝试过循环设备并将它们添加到设备列出来看看这是否会改变你的回报?此外,您的 resJson 是一个对象,而不是像您的目标 JSON 那样的数组。
  • 感谢您的关注,我试过了,我编辑了我的帖子。

标签: arrays database json node.js control-flow


【解决方案1】:

也许您可以使用after 类型的构造来代替跟踪和使用针对列表长度的索引。我真的很喜欢它们,它们很容易集成,并且在一定次数后为做某事提供完美的目的。

首先,让我们定义一个可以使用的 after 函数。

var after = function(amount, fn) {
  var count = 0;
  return function() {
    count += 1;
    if (count >= amount) {
      fn.apply(arguments);
    }
  };
};

现在应该对你有用,让我们修改你的代码示例以使用它。

var json = []; // To return, you originally wanted an array.
Group.all(function(err, groups) {
  if (err) {
    // Handle the error
  } else {
    var sendJson = after(groups.length, function(json) {
      send({code: 200, data: json});
    });
    groups.forEach(function(group) {
      group.devices(function(err, devices) {
        if (err) {
          // Handle the error...
        } else {
          group.devices_list = devices;
          json.push(group); // This part is different, using this method you'll match the JSON you gave as your "goal"
        }
        // This is outside the if/else because it needs to be called for every group
        // regardless of change. If you do not call this the exact number of times
        // that you specified it will never fire.
        sendJson(json);
    });
  }
});

也许这样的事情可以解决你的问题。

【讨论】:

  • 感谢您的帮助 izuriel,它正在工作!实际上,该指数不可靠地做到这一点。后功能很棒。
猜你喜欢
  • 2014-12-01
  • 2015-05-26
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 2021-05-16
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多