Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

294
Visualizações
node.js variable not surviving code block

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)
   };
};
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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)
   };
};
over 4 years ago · Santiago Trujillo Relatório

0

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)
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda