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);
}
});
};
2
Answers
Here's the new, working, version of the function:
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.