0

I am new to javascript and have trouble reading a value back from

var ls = require('list-directory-contents');
var movies = [];

ls(__dirname + '/movies', function(error, files){
   movies = files;
});

console.log(movies);  // logs ---> []

From the code above I can see that the ls function (imported via npm install list-directory-contents) has a callback function - so my problem is lack of understanding these and promises? I am confused as to how can I work with the files? Do I have to write all my code inside the ls function call? That seems a bit nasty?

Any help is greatly appreciated and I apologise in advance if this is too easy to answer :)

Ben
  • 74
  • 3
  • 3
    `movies = files;` will be executed asynchronously which mean at a future undetermined time, so the execution of the main method will continue before the callback is executed that is why the console log is returning empty array, all processing that deals with the directory listing need to be done within the callback – Arun P Johny Apr 06 '16 at 03:20
  • Call `console.log(movies);` or anything else that needs `movies` **inside** the `function(error, files)` callback where it is defined. Insisting on writing code in an imperative style causes these difficulties. Adapt. – Paul Apr 06 '16 at 03:21

0 Answers0