Published on

Howto Return Values With the Redis NodeJS Client

Authors

One of the most popular NodeJS Redis clients is this one. Using it is fairly straight forward whatever Redis command there is is exposed with exactly the same name on the client. So for example if I want to use ZRANGE I simply call it using:

import redis from "redis";

const redisClient = redis.createClient();

...
redisClient.zrange('myCollectionName',0, - 1, function(err, response){
    if(err) {
        console.error(err);
        throw err;
    }
    // do whatever you need to with response
});

This is cool but what was not immediately clear is how do you return the response object in the above so you can use it elsewhere?

Using const result await = redisClient.zrange('myCollectionName', 0, - 1); will not work. After reading through the README more carefully it looks like you need to use a promise library like Bluebird or wrap whatever functions you want to use asynchronously yourself using the native nodejs promises. I opted for the former option as I did not want to have to do this for every function I wanted to use and instead just have it available for all functions.

I did this by:

  • First installing bluebird:
yarn add bluebird
  • Changing how I initialize the redis client slightly by creating a new file called redisClient.js:
import redis from 'redis'
import bluebird from 'bluebird'

bluebird.promisifyAll(redis)

export const redisClient = redis.createClient()

The above does not have to be in a separate file but doing so makes it much easier to use as you do not have to promisifyAll wherever you want to use it and you can centralize the creation allowing you to easily change the host and port if needed.

Now using this is exactly as you would expect accept that whatever redis function you want to use has to be suffixed with Async. For example redisClient.zrange becomes redisClient.zrangeAsync. The example from earlier can now be written as:

import { redisClient } from "./redisClient";

...
const results = await redisClient.zrangeAsync('myCollectionName',0, - 1);