How can I access the key passed to hgetall when using node_redis?

删除回忆录丶 提交于 2019-12-06 12:07:31

You need to use a closure to store user_id by introducing a function in the loop. One way to do it is to use the forEach function to iterate on the array.

Here is an example in 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));
});

The output is:

[ {"user:2":{"name":"user2","password":"secret2"}},
  {"user:1":{"name":"user1","password":"secret"}} ]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!