Leuel Asfaw
Leuel Asfaw

Reputation: 339

Why is client.isReady returning undefined in my redis client connection

I have the following RedisClient class that connects to a redis server:

import { promisify } from 'util';
import { createClient } from 'redis';

class RedisClient {
  constructor() {
    this.client = null;
  }

  async initialize() {
    this.client = RedisClient.getRedisClient();
    await this.waitForReady();
  }

  static getRedisClient() {
    return createClient();
  }

  async waitForReady() {
    return new Promise((resolve, reject) => {
      this.client.on('error', (err) => console.log(`Redis: ${err}`, reject));
      this.client.on('ready', () => console.log('Redis connected'), resolve);
    });
  }

  isAlive() {
    return this.client.isReady;
  }
}

const redisClient = new RedisClient();

(async () => {
  await redisClient.initialize();
})();

export default redisClient;

I want the redis client to be ready before I used it that is why i created the waitForReady function to await the creation of the redis client. I tested it with this code:

import redisClient from './utils/redis';

(async () => {
  console.log(redisClient.isAlive());
})();

But I am getting an undefined output to the console log. Why is happening I have tried to make the creation of the redis client asynchronous but still I am getting undefined. Is it because the isReady is deprecated or should I use the isOpen instead?

Update I am using redis 2.8.0

Upvotes: 0

Views: 883

Answers (2)

Katrina Rodriguez
Katrina Rodriguez

Reputation: 1

Checking out at the node-redis examples documentation, it looks like isReady is still valid. You could use isOpen or isReady to check the redis client connection.

// isOpen will return True here as the client's socket is open now.
// isReady will return True here, client is ready to use.
console.log(`client.isOpen: ${client.isOpen}, client.isReady: ${client.isReady}`);

Upvotes: 0

Guy Royse
Guy Royse

Reputation: 4332

Looks like you are using Node Redis. When using Node Redis, you must connect to the client after creating it.

Like this:

await this.client.connect()

There is newer syntax for this in the README which I haven't tried yet but that looks pretty slick:

import { createClient } from 'redis';

const client = await createClient()
  .on('error', err => console.log('Redis Client Error', err))
  .connect();

await client.set('key', 'value');
const value = await client.get('key');
await client.disconnect();

Upvotes: 0

Related Questions