how to wait till the response is received from redis in node?


how to wait till the response is received from redis in node?



I am new to node and redis.I am using redis in my node application.I want to retreive
data from redis in a synchronous fashion.Here is what I tried.


var redis = require("redis"),
client = redis.createClient();

client.set('key',10,redis.print);

function getfn1(key){
client.get(key,function(err,reply){
if(err){
console.log('Response from getfn1:-');
console.log(err);
return;
}
console.log('Response from getfn1:-');
console.log(reply);
});
}

async function getfn2(key){
let response = await client.get(key);
console.log('Response from getfn2:-');
console.log(response);
}
console.log('1');
getfn1('key');
console.log('2');
getfn2('key');
console.log('3');



The result is as follows:


1
2
3
Response from getfn2:-
false
Response from getfn1:-
10



As you can see I am trying to wait for the result from redis using async and await in getfn2() but I get a response of 'false' instead of the original response of 10.It would be better if you suggested a method of waiting for data from redis.




1 Answer
1



The async/await syntax is meant to be used with Promises, but the redis module does not return Promises by default.


async/await



If you want to use Promises, this is what the documentation says to do:



You can also use node_redis with promises by promisifying node_redis
with bluebird as in:


var redis = require('redis');
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);



It'll add a Async to all
node_redis functions (e.g. return client.getAsync().then())


// We expect a value 'foo': 'bar' to be present
// So instead of writing client.get('foo', cb); you have to write:
return client.getAsync('foo').then(function(res) {
console.log(res); // => 'bar'
});



Your getfn2 function would then become:


getfn2


async function getfn2(key){
let response = await client.getAsync(key);
console.log('Response from getfn2:-');
console.log(response);
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV