我有一个node.js(快速)应用程序,并且我正在使用node_redis从Redis数据库中获取所有用户。
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。
您需要通过在循环中引入一个函数来使用闭包来存储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"}} ]