Home > Software engineering >  node.js variable not surviving code block
node.js variable not surviving code block

Time:04-01

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)
   };
};

CodePudding user response:

The problem is due to promises. Your handler execution is completing before redis is returning the result. Following snippet should work:

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;
   
   try{
       resultValue = await redis.get(key);
   }catch(error) {
       errorValue = error;
   }

   response={
      key: key,
      resultValue: resultValue,
      errorValue: errorValue
   };
   
   return {
      statusCode: 200,
      body: JSON.stringify(response)
   };
};

CodePudding user response:

It is because your call to "redis.get" is not resolved when "response" is sent.

You need to wait for the response :

await new Promise((resolve) => {
    redis.get(key, (err, result) => {
        if (err) {
           errorValue=err;
        } else {
           resultValue=result;
        }
        resolve();
     });
})

or even better turn the redis response into a promise response :

await new Promise((resolve, reject) => {
    redis.get(key, (err, result) => {
        if (err) {           
           reject(err);
        } else {
           resolve(result);
        }
    })
})
  .then((result) => resultValue = result)
  .catch((err) => errorValue = err)
  • Related