skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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');
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search