Redis use sync/await keywords on

10,268

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

Solution 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');

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

Share:
10,268
Admin
Author by

Admin

Updated on June 24, 2022

Comments

  • Admin
    Admin almost 2 years

    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.

  • myNewAccount
    myNewAccount over 3 years
    +1 because the concept is 100% correct. But isn't that first client.get supposed to be below const client?
  • pedro casas
    pedro casas about 3 years
    const redisGet = util.promisify(db_redis.SCAN).bind(db_redis);