Home > front end >  Function meant to send data to Redis server sends the data, but will not send success response
Function meant to send data to Redis server sends the data, but will not send success response

Time:01-28

My setJWT function sends a key/value pair to my local Redis server. I've confirmed the data is set with the redis-cli tool. However, the console.log("setJWT success") and res.json(response); in the function aren't triggered.

Any idea what I'm doing wrong?

const redis = require('redis');
const client = redis.createClient(process.env.REDIS_URL);

client.connect();

client.on('connect', () => {
    console.log('connected');
});

const setJWT = (key, value) => {
  
  return new Promise((resolve, reject) => {
    try {
      console.log(key, value)
      return client.set(key, value, (error, response) => {
        
        if (error) reject(error);
        resolve(response);
        console.log("setJWT success");
        res.json(response);
      });
    } catch (error) {
      reject(error);
    }
  });
};

CodePudding user response:

there are a lot of things that don't look correctly, firstly you are referencing the variable res, but It doesn't exist in your code, also it's not necessary to wrap everything in a promise, you can use an async/await function, after your resolve or reject a promise the code finish, for that reason never the res.json code is executed, because the promise finished before that line of code, in this link you can see an example of redis in more details.

CodePudding user response:

Here's the new, working, version of the function:

  const setJWT = (key, value) => {
  try {
    client.set(key, value);
    console.log("setJWT success");
  } catch (error) {
    console.log(error);
  }
};
  •  Tags:  
  • Related