I’m experimenting with Node.js in AWS Lambda. And, I’ve run into a problem with the code below. Result value and error value are always returned blank. I’m pretty sure this is just a scope issue I’m to tired to see. How do I capture the return value and pass it back in the response? I’m sure the programs is connecting to redis because I get an error message if I change the port or URL and I don’t when they’re set properly.
The return code:
{
"statusCode": 200,
"body": "{"key":"q1"}"
}
The program code:
const Redis = require("ioredis");
const redis = new Redis(6379, 'fredflenstone.lhpxwy.az.0002.use2.cache.amazonaws.com');
exports.handler = async(event)=>{
let key=event.key;
let response;
let resultValue;
let errorValue;
redis.get(key, (err, result) => {
if (err) {
errorValue=err;
} else {
resultValue=result;
}
});
response={
key: key,
resultValue: resultValue,
errorValue: errorValue
};
return {
statusCode: 200,
body: JSON.stringify(response)
};
};
2
Answers
It is because your call to "redis.get" is not resolved when "response" is sent.
You need to wait for the response :
or even better turn the redis response into a promise response :
The problem is due to promises. Your handler execution is completing before redis is returning the result. Following snippet should work: