Dave Brady
Dave Brady

Reputation: 203

value not setting in the variable which is defined outside in NodeJS

I'm new to NodeJS so please apologize if below code is not up-to the standard. I would like to access isSuccess value outside of this function stepfunctions.listExecutions

I tried below code but I'm getting the value is undefined not getting the expected output. I did some internet search and came to know in NodeJS we can't set the value which is defined in globally but I've use case and I'm pretty sure this is a common case for others too - where I would like to access this isSuccess value after my execution.

  const AWS = require('aws-sdk');

  const stepfunctions = new AWS.StepFunctions({
    region: process.env.AWS_REGION
  });

  
  var params = {
    stateMachineArn: 'arn:aws:states:us-west-1:121:stateMachine:test',
    maxResults: '2',
    nextToken: null,
    statusFilter: 'SUCCEEDED'
  };


var isSuccess
stepfunctions.listExecutions(params, function (err, data) {
    if (err) console.log(err, err.stack);
    else
      data.executions.forEach(function (result) {
        let params = {
          executionArn: result.executionArn
        };
        stepfunctions.describeExecution(params, function (err, data) {
          if (err) console.log(err, err.stack);
          else {
            isSuccess = 'true'
          }
        });

      });

      console.log('isSuccess: ' +isSuccess)

  });

Expected output:

isSuccess: true

But I'm getting

isSuccess: undefined

Could you please help me to resolve this issue. Appreciated your help and support on this.

Upvotes: 1

Views: 75

Answers (1)

Indraraj26
Indraraj26

Reputation: 1966

This is how you can wrap it on promise

let isSuccess;

const listExecute = function(params) {
  return new Promise((resolve, reject) => {
    stepfunctions.listExecutions(params, function (err, data) {
    if (err) reject(err);
    else
      data.executions.forEach(function (result) {
        let params = {
          executionArn: result.executionArn
        };
        stepfunctions.describeExecution(params, function (err, data) {
          if (err) reject(err);
          else {
            resolve(true)
          }
        });

      });
  });
  })
}


async function getOutout(params) {
  try {
    isSuccess = await listExecute(params);
    console.log(isSuccess, 'Output')
  } catch(e) {
    console.log(e)
  }
}

getOutout(params)

Also you can export the listExecute so that you can use this function outside of this file.

module.exports = {listExecute}

Upvotes: 2

Related Questions