0

I am trying to access returned values from an asynchronous function but I keep getting undefined. I have tried a ton of suggestions from SO but cant seem to get what I need. I want to be able to access the values in the logs array.

const jsonPath = '';

let logs = [];
function getLogs(folderPath, callback){
    fs.readdir(folderPath, (err, files) => {
        if(!err){
            files.forEach(file => {
                let response = fs.readFileSync(folderPath + '/' + file, 'utf8')
                logs.push(JSON.parse(response).changelog);
            })
        }
        else{
            console.log('Error: ' + err);
        }
        callback(logs);
    })
}

getChangelogs(jsonPath, function(result){
  return logs; //I want to be able to access this logs array
})
begprog
  • 271
  • 1
  • 2
  • 8
  • `fs.readdir()` is **asynchronous**. The callback will be invoked when the contents are available, but the call to `.readdir()` itself returns immediately. – Pointy Mar 18 '19 at 16:39
  • What are the contents of your file? Post a sample. – Prerak Sola Mar 18 '19 at 16:40
  • @PrerakSola it would be something like { "value1": "value", "value2": "value2" } – begprog Mar 18 '19 at 16:52
  • @Pointy I'm still a bit confused on what to do. – begprog Mar 18 '19 at 16:56
  • The callback function is where you'll have access to the file contents. – Pointy Mar 18 '19 at 17:00
  • @Pointy I understand that, but if I push the values in the callback, how will I be able to see that array? – begprog Mar 18 '19 at 17:02
  • I changed the question, can someone please help – begprog Mar 18 '19 at 17:51
  • Look at the linked duplicate: *you cannot do what you want to do.* You have to structure your application such that activity happens in response to the progress of asynchronous activity. There are various ways of doing that: simple callbacks like you've got, Promises, and in newer environments `async`/`await`. – Pointy Mar 18 '19 at 18:32

0 Answers0