I have a node.js (express) application and I'm using node_redis to get all users from my 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
This produces the following result:
[
{
"name": "user1",
"password": "secret"
},
{
"name": "user2",
"password": "secret"
}
]
Now I want the user_id to be added to the user result, so I can get the following output:
[
{
"user:1": {
"name": "user1",
"password": "secret"
}
},
{
"user:2": {
"name": "user2",
"password": "secret"
}
}
]
The problem I have is that client.hgetall() is called asynchronously and I can't simply access the user_id in the for loop.
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:
The output is: