0

I am having troubles accessing values from within a callback function in parent/outer scope. Basically I want to access the data that the following s3.getObject() function fetches and use it in outer scope (last line).

I have the following javascript code to fetch some data from AWS:

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

AWS.config.update({
    //ids
})

const s3 = new AWS.S3()


/* actual parameters should go here */
const params = {
  Bucket: "test-ashish-2019", 
  Key: "dummy.csv"
};

const parseOptions = {
  header: true,
  dynamicTyping: true
}

s3.getObject(params, function(err, data) {
if (err)  console.log(err, err.stack);
//   else {console.log(data)};
else {
    const csv = data.Body.toString('utf-8'); 
    const headers = 'id,start,end,count';
    const parsed = Papa.parse(headers + '\n' + csv, parseOptions);
    var csvdata = parsed.data;
    console.log(csvdata); //this is working as expected
    }

});

console.log(csvdata); //not working as expected

How do I make the last line work?

azrael v
  • 281
  • 5
  • 17

2 Answers2

0

You can't access that variable outside of the callback scope because the callback is happening asynchronously (your last line is actually being called before csvdata gets set by the callback).

You'll have to pass that data along a promise chain (or use async/await) to use it outside the callback context.

Adam Coster
  • 1,162
  • 1
  • 9
  • 16
0

Your problem is your code executes immediately before the callback is called and s3.getObject returns a promise so you can utilize the promise this way:

Refactor your code to this:

const getS3Object = async () => {

const data = await s3.getObject(params);
const csv = data.Body.toString('utf-8'); 
const headers = 'id,start,end,count';
const parsed = Papa.parse(headers + '\n' + csv, parseOptions);
var csvdata = parsed.data;
console.log(csvdata); //this is working as expected
}

console.log(csvdata); //will work
Rami
  • 490
  • 7
  • 22