Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 577
Giedrius Avatar asked Nov 15 '12 01:11

Giedrius


People also ask

How do node promises work?

A Promise in Node means an action which will either be completed or rejected. In case of completion, the promise is kept and otherwise, the promise is broken. So as the word suggests either the promise is kept or it is broken. And unlike callbacks, promises can be chained.

How do I start Redis on node JS?

Create new session. js file in the root directory with the following content: const express = require('express'); const session = require('express-session'); const redis = require('redis'); const client = redis. createClient(); const redisStore = require('connect-redis')(session); const app = express(); app.

Does node js support promise?

In Node. js, we can use the util. promisify() utility module to easily transform a standard function that receives a callback into a function that returns a promise.

What is promise in Express JS?

A promise is commonly defined as a proxy for a value that will eventually become available. Promises are one way to deal with asynchronous code, without getting stuck in callback hell.


1 Answers

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

like image 168
Dan D. Avatar answered Oct 12 '22 17:10

Dan D.