0

这是一个片段:

objects = [];
client.keys 'objects*', (err,keys) ->
for (i = 0; i < keys.length; i++){
  client.hgetall(keys[i], function(err, obj) {
    objects.push(obj);
    if (i === keys.length){
      response.writeHead(200, {'Content-Type': 'application/json'});
      console.log(JSON.stringify(objects));
      response.write(JSON.stringify(objects));
      response.end();
    }
  }
}

var对象是我通过 node-redis 查询 redis 填充的对象数组,每个对象有 6 个属性。在控制台中,我得到了我所期望的。但是,在客户端中,我收到一个仅包含最后一个对象的数组。想知道它是否是客户端的解串器,我在 Fiddler 中捕获了它,它仍然是带有单个对象的数组。

这是我通过 console.log 在控制台中得到的:

[{"prop1":"11","prop2":"12","prop3":"13","prop4":"14","prop5":"15","prop6":"16"},  {"prop1":"21","prop2":"22","prop3":"23","prop4":"24","prop5":"25","prop6":"26"},{"prop1":"31","prop2":"32","prop3":"33","prop4":"34","prop5":"35","prop6":"36"},{"prop1":"41","prop2":"42","prop3":"43","prop4":"44","prop5":"45","prop6":"46"},{"prop1":"51","prop2":"52","prop3":"53","prop4":"54","prop5":"55","prop6":"56"},{"prop1":"61","prop2":"62","prop3":"63","prop4":"64","prop5":"65","prop6":"66"}]

我一定做错了什么...

4

1 回答 1

1

您的异步代码是错误的。if (i === keys.length) 行将始终返回 true,因为您正在检查 client.hgetall 是否已被调用 keys.length 次,而不是调用是否已完成。你应该检查 (objects.length === keys.length) – DeaDEnD

于 2013-03-12T22:50:38.393 回答