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
(async () => { await redisClient.initialize(); })();" is pointless, that launches an anonymous task but does not wait for it. Same as just writingredisClient.initialize();. It is still exported before the client is done initialising. You would need to use top-levelawaitin the module to achieve that.