0

The below code not returning amazon s3 content, it works when console the data value. I have tried declare variable outside function and tried to return from function still, not works

const getMeridianToken1 = () =>{

  s3 = new aws.S3();

  // Create the parameters for calling listObjects
  var bucketParams = {
    Bucket: 'bucket-name',
    Key: 'access_token.json'
  };

  // Call S3 to obtain a list of the objects in the bucket
  s3.getObject(bucketParams, function(err, data) {
    if (!err) {
      var result = JSON.parse(data.Body.toString());
      console.log("working here---",result.access_token);
      return result.access_token; //this is not returning
    }
  });
  //return JSON.parse(data.Body.toString()); //if hard code here it works, if i return s3 conteent the data variable not available here
}

console.log("not working",getMeridianToken1);
jayavel
  • 23
  • 5

2 Answers2

0

s3.getObject is a asychronous call the control reaches on return JSON.parse() line early which is why data variable is not available outside the callback function.

Solution is to wrap s3.getObject in promise or use async/await.

0

The issue is the s3 method being asynchronous. See this

function getMeridianToken1() {
  const s3 = new aws.S3();

  // Create the parameters for calling listObjects
  var bucketParams = {
    Bucket: 'bucket-name',
    Key: 'access_token.json'
  };
  return new Promise((resolve, reject) => {
    s3.getObject(bucketParams, function(err, data) {
      if (!err) {
        var result = JSON.parse(data.Body.toString());
        resolve(result.access_token);
      }
      reject(err);
    });
  });
}

getMeridianToken1()
  .then(val => console.log(val));

Hope this helps

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35