使用node_redis时,如何访问传递给hgetall的密钥?

时间:2012-10-08 14:21:55

标签: node.js redis node-redis

我有一个node.js(express)应用程序,我正在使用node_redis从我的redis db中获取所有用户。

redis = require "redis"
client = redis.createClient()

client.smembers "users", (err, user_ids) ->
  results = new Array()
  for user_id in user_ids
    client.hgetall user_id, (err, items) ->
      results.push items
      if user_ids.length is results.length
        res.json results

这会产生以下结果:

[
  {
    "name": "user1",
    "password": "secret"
  },
  {
    "name": "user2",
    "password": "secret"
  }
]

现在我想将user_id添加到用户结果中,因此我可以得到以下输出:

[
  {
    "user:1": {
      "name": "user1",
      "password": "secret"
    }
  },
  {
    "user:2": {
      "name": "user2",
      "password": "secret"
    }
  }
]

我遇到的问题是异步调用 client.hgetall(),我不能简单地访问for循环中的user_id。

1 个答案:

答案 0 :(得分:4)

您需要使用闭包来通过在循环中引入函数来存储user_id。一种方法是使用forEach函数迭代数组。

以下是Javascript中的示例:

var redis = require('redis')
var client = redis.createClient();

function fetch( callback ) {
   var results = new Array();
   client.smembers( "users", function(err,users) {
      if ( users.length == 0 )
         return callback( results );
      users.forEach( function(id) {
         client.hgetall(id, function(err,items) {
            var obj = {};
            obj[id] = items; # here id can be accessed since it is part of the closure
            results.push(obj);
            if ( results.length == users.length ) {
               callback( results );
            }
         });
      });
   });
}

fetch( function(results) {
   console.log(JSON.stringify(results));
});

输出结果为:

[ {"user:2":{"name":"user2","password":"secret2"}},
  {"user:1":{"name":"user1","password":"secret"}} ]