0

I have implemented redis cache in my node server.I am running redis docker container locally.I have keys stored in redis container which I am able to see but when I am trying to access then I am failed to get data.

Below is my code:

const redis = require('redis');

let redisClient;

redisClient = redis.createClient('127.0.0.1', 6379);

redisClient.connect();

redisClient.on('error', err => {
  console.log('Error ' + err);
});

redisClient.on('connect', () => {
  console.log('Connected to Redis');
});

 //Saving data here
 redisClient.set('Region', 'Asia', (err, reply) => {
 if (err) {
     console.log('error', err);
 }
 else {
     console.log(reply);
 }
});

//Fetching data here
redisClient.get('Region', (err, reply) => {
 if (err) {
    console.log('error', err);
 }
 else {
    console.log(reply);
 }
});

Here even though data is saved successfully in redis but I am not getting console statement after saving data.And I am also unable to fetch data from redis.I am only getting Connected to Redis console log.

Someone let me know what I have done wrong in my code.So far to me code seems fine.

Digvijay
  • 2,887
  • 3
  • 36
  • 86
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Matt Feb 08 '23 at 08:16
  • 2
    You are calling `get` before the `set` even finished, but even more, you are calling both `set` and `get` before the connection is even established. – CherryDT Feb 08 '23 at 08:21

1 Answers1

1

It looks like you are using the node-redis client. In v4, this supports promises. Using promises with async/await should make your code easier to follow:

import { createClient } from 'redis';

try {
  const client = createClient();

  await client.connect();

  await client.set('Region', 'Asia');
  const region = await client.get('Region');

  console.log(`Region is ${region}`);

  await client.quit();
} catch (e) {
  console.error('Oh no:');
  console.error(e);
}
Simon Prickett
  • 3,838
  • 1
  • 13
  • 26