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.

2
  • Does this answer your question? How do I return the response from an asynchronous call? Commented Feb 8, 2023 at 8: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. Commented Feb 8, 2023 at 8:21

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.