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.
3
Answers
You can use util node package to promisify the get function of the client redis.
With the util package i modified the get function to return a promise.
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:
It’ll add a Async to all node_redis functions (e.g. return client.getAsync().then())
This example uses bluebird promisify read more here
So after you promsified a
get
to ‘getAsync’ you can use it in async awaitso in your case
For TypeScript users both
util.promisify
andbluebird.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.