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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With