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
2
Answers
Looks like you are using Node Redis. When using Node Redis, you must connect to the client after creating it.
Like this:
There is newer syntax for this in the README which I haven’t tried yet but that looks pretty slick:
Checking out at the node-redis examples documentation, it looks like
isReady
is still valid. You could useisOpen
orisReady
to check the redis client connection.