Home > Back-end >  NodeJS why won't my function be called inside my IF/Else statement
NodeJS why won't my function be called inside my IF/Else statement

Time:11-29

I have a question around node and calling a function inside of if/else statements. Below is my situation. I'm not sure why calling the awsCreds function works from the first IF statement, but it doesn't work when I try to invoke it from the else statement. Does it have something to do with the fact I have an if/else inside of an else statement?

let cacheExpiration;
let currentTime;
let awsCredentials;

async function stsGetCallerIdentity(creds, message) {
   const stsParams = { credentials: creds };
   // Create STS service object
   const kinesis = new AWS.Kinesis(stsParams);
   const parsed_value = JSON.parse(message);
   const type = parsed_value.type;
   console.info(type);

   const message_type = {
      "transcript": process.env.TRANSCRIPT_KINESIS,
      "tone": process.env.TONE_KINESIS,
      "pitch": process.env.PITCH_KINESIS
   };
   const stream_name = message_type[type];
   console.info(stream_name);

   const params = {
      Data: Buffer.from(message),
      PartitionKey: `1111`,
      StreamName: stream_name
   };
   kinesis.putRecord(params, function(err, data) {
      if (err) console.error(err);
      else {
         console.info(JSON.stringify(data));
      }
   });
}

function awsCreds() {
   return new Promise((resolve, reject) => {
      const roleToAssume = {
         RoleArn: process.env.IAMRole,
         RoleSessionName: `session1`,
         DurationSeconds: 900 };

      sts.assumeRole(roleToAssume, function(err, data) {
         if (err) {
            console.error(err, err.stack);
            reject(err.stack);
         } else {
            awsCreds = {
               accessKeyId: data.Credentials.AccessKeyId,
               secretAccessKey: data.Credentials.SecretAccessKey,
               sessionToken: data.Credentials.SessionToken,
               cacheExpiration: data.Credentials.Expiration
            };
            resolve(awsCreds);
         }
      });
   });
};

webSocketClient.on(`message`, async (message) => {
try {
  currentTime = new Date();
  console.log(`currentTime`, currentTime);
  console.log(`cacheExpiration`, cacheExpiration);


          if (cacheExpiration == undefined) {
            //Calling awsCreds returns values.
           awsCredentials = await awsCreds();
           stsGetCallerIdentity(awsCredentials, message)
    
        } else {
           const minutes = (cacheExpiration.getTime() - currentTime.getTime());
           console.log(`minutes`, minutes);
           if (minutes > 60000) {
              //Do something
           stsGetCallerIdentity(awsCredentials, message)
           } else {
              
              // Calling awsCreds from here returns error 'awsCreds is      not a function'.
console.log(`Refreshing credentials`);
              awsCredentials = await awsCreds();
              stsGetCallerIdentity(awsCredentials, message)
           }
        }
       
     } catch (error) {
        console.error(`There was an error`, error);
     };
)};

CodePudding user response:

Your function is called awsCreds, and then you assign awsCreds as an object literal before you resolve, you need const in front, or don't assign at all just put the object inside resolve:

Change

awsCreds = {
   accessKeyId: data.Credentials.AccessKeyId,
   secretAccessKey: data.Credentials.SecretAccessKey,
   sessionToken: data.Credentials.SessionToken,
   cacheExpiration: data.Credentials.Expiration
};
resolve(awsCreds);

To

resolve({
   accessKeyId: data.Credentials.AccessKeyId,
   secretAccessKey: data.Credentials.SecretAccessKey,
   sessionToken: data.Credentials.SessionToken,
   cacheExpiration: data.Credentials.Expiration
});
  • Related