0

Here is a snippet:

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();
    }
  }
}

The var objects is an array of objects I populate by querying redis via node-redis, each with 6 properties. In the console, I get exactly what I would expect. In a client, however, I receive an array with only the last object. Wondering if it was the client's deseralizer, I captured it in Fiddler and it is still that array with a single object.

Here is what I get in the console via 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"}]

I must be doing something wrong...

5
  • Can you give an example of the object being serialized? Commented Jan 12, 2012 at 16:41
  • I edited my question to include more detail and hopefully address your comment. Also, I originally (incorrectly) stated I was only seeing the first object, when in fact I am only getting the last one. Commented Jan 12, 2012 at 17:07
  • Your async code is wrong. The line if (i === keys.length) will always return true because you are checking if client.hgetall has been called keys.length times and not if the calls have been completed. You should instead be checking (objects.length === keys.length) Commented Jan 13, 2012 at 16:54
  • Thanks @DeaDEnD. Changing this did work, so if you want to put it as an answer I will use it. This async stuff is kind of new to me, so my thinking wasn't in that lane. Thanks again! Commented Jan 16, 2012 at 17:24
  • I dislike coffeescript. Commented Mar 12, 2013 at 22:56

1 Answer 1

1

Your async code is wrong. The line if (i === keys.length) will always return true because you are checking if client.hgetall has been called keys.length times and not if the calls have been completed. You should instead be checking (objects.length === keys.length) – DeaDEnD

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.