Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis use sync/await keywords on

I am new in the JS world, I am creating a query cache and I decide to use redis to cache the information, but I want to know if there is a way to use async/await keywords on the get function of redis.

const redis = require('redis');
const redisUrl = 'redis://127.0.0.1:6379';
const client = redis.createClient(redisUrl);
client.set('colors',JSON.stringify({red: 'rojo'}))
client.get('colors', (err, value) => {
    this.values = JSON.parse(value)
})

I want to know if I can use the await keyword instead of a callback function in the get function.

like image 956
eliasGrullon25 Avatar asked Jan 02 '20 00:01

eliasGrullon25


3 Answers

You can use util node package to promisify the get function of the client redis.

const util = require('util');
client.get = util.promisify(client.get);
const redis = require('redis');
const redisUrl = 'redis://127.0.0.1:6379';
const client = redis.createClient(redisUrl);
client.set('colors',JSON.stringify({red: 'rojo'}))
const value = await client.get('colors')

With the util package i modified the get function to return a promise.

like image 69
Luis Louis Avatar answered Oct 21 '22 17:10

Luis Louis


For TypeScript users both util.promisify and bluebird.promisifyAll aren't ideal due to lack of type support.

The most elegant in TypeScript seems to be handy-redis, which comes with promise support and first-class TypeScript bindings. The types are generated directly from the official Redis documentation, i.e., should be very accurate.

like image 25
bluenote10 Avatar answered Oct 21 '22 17:10

bluenote10


This is from redis package npm official documentation

Promises - 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'
});
 
// Using multi with promises looks like:
 
return client.multi().get('foo').execAsync().then(function(res) {
    console.log(res); // => 'bar'
});

This example uses bluebird promisify read more here

So after you promsified a get to 'getAsync' you can use it in async await so in your case

const value = await client.getAsync('colors');
like image 45
Rami Loiferman Avatar answered Oct 21 '22 16:10

Rami Loiferman