skip to Main Content

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


  1. 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)
    
    Login or Signup to reply.
  2. 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)
       };
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search