Search code examples
node.jsredispromiseq

nodejs redis Q promises, how to make it work?


I am trying to get few values from redis, combine them and eventually send. But I just can't make those promises work.

This is the simple get functions from redis

client.get('user:1:id',function(err,data){
    // here I have data which contains user ID
});
client.get('user:1:username',function(err,data){
    // here I have data which contains username
});

Now I want to get ID and username and send them, but I have no idea how to make that work. I manage to make it work with callbacks but it is very messy result, so then i tried to wrap anonymous functions into Q.fcall and after call .then which looks something like that

client.get('user:1:id',Q.fcall(function(err,data){
    return data;
}).then(function(val) {
   // do something
}));

but that gives me error for too many arguments been passed and I'm not even sure if that would help me even if it would work.


Solution

  • Q.all([Q.ninvoke(client, 'get', 'user:1:id'),
           Q.ninvoke(client, 'get', 'user:1:username')]).then(function (data) {
      var id = data[0];
      var username = data[1];
      // do something with them
    });
    

    See https://github.com/kriskowal/q#adapting-node