【问题标题】:node_redis : using client.multi within forEachnode_redis :在 forEach 中使用 client.multi
【发布时间】:2012-05-09 14:31:18
【问题描述】:

我有以下代码应该检索设备列表并获取每个设备的状态和标签:

app.get('/test', function(req, res){
  db.smembers("devices", function(err1, devices){
    var jsonObj = {};
    if(!err1) {
       var i = 0;
       devices.forEach(function(id){
          db.multi([
             ["get", id + ":label"],
             ["get", id + ":status"],
          ]).exec(function (err, replies) {
             jsonObj[id] = {"label":replies[0], "status":replies[1]};
             console.log(jsonObj);     // stuff is added on each loop
          });

          i = i + 1;
          if(i == devices.length){  
             console.log(jsonObj);     // jsonObj is {}     
             h.respond(res, jsonObj);
          }
       });
    } else {
       h.respond(res, { "error" : err1 });
    }
  });
});

devices 是一个 id 列表。对于每个 id,有 2 个键:“ID:status”、“ID:label”

h.respond 是一个发送 http 响应的辅助方法。

我可以看到每个循环都将新数据添加到 jsonObj,但是当所有循环完成时,它是空的。

【问题讨论】:

  • 遇到了类似的问题。好问题

标签: node.js redis node-redis


【解决方案1】:

代码异步运行,并且在任何 Redis 调用实际完成之前计数到 devices.length(它不会等待来自multi 的回调在继续之前返回)。将您的支票移到回调中可以防止这种情况发生。

app.get('/test', function(req, res){
  db.smembers("devices", function(err1, devices){
    var jsonObj = {};
    if(!err1) {
       var i = 0;
       devices.forEach(function(id){
          db.multi([
             ["get", id + ":label"],
             ["get", id + ":status"],
          ]).exec(function (err, replies) {
             jsonObj[id] = {"label":replies[0], "status":replies[1]};
             console.log(jsonObj);     // stuff is added on each loop
             i = i + 1;
             if(i == devices.length){  
                console.log(jsonObj);     // jsonObj is {}     
                h.respond(res, jsonObj);
             }
          });


       });
    } else {
       h.respond(res, { "error" : err1 });
    }
  });
});

将这段代码移到一个单独的函数中可能更有意义,但希望您明白这一点。像 async 这样的异步库提供了帮助方法,可以更轻松地执行这样的并行异步循环。

【讨论】:

  • 那时我还没有处于正确的回调级别,非常感谢现在工作正常!
  • 很好看!我支持async 的推荐。我不能推荐这个库,它确实有助于以最小的复杂性清理这种流控制。
猜你喜欢
  • 1970-01-01
  • 2011-07-05
  • 2014-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 1970-01-01
相关资源
最近更新 更多