0

I know that this thing was already questioned, but really, I have not found anything useful or understandable.

I have this code:

var pdfListPath = [];

function listDir(path) {
  window.resolveLocalFileSystemURL(path,
    function(fileSystem) {
      var reader = fileSystem.createReader();
      reader.readEntries(
        function(entries) {
          console.log(entries);
          for (var i = 0; i == entries.length; i++) {
            pdfListPath.push(entries[i]);
          };
        },
        function(err) {
          console.log(err)
        }
      );
    },
    function(err) {
      console.log(err);
    }
  );
};

var pdfList = listDir(cordova.file.applicationDirectory + "www/pdf/");
console.log(pdfList);
console.log(pdfListPath);

What I expected was the pdfListPath filled with something, but what I get in the console is an "undefined."

The entries instead is a filled array, so what is wrong with this?

Thank you in advance.

freginold
  • 3,946
  • 3
  • 13
  • 28
Pds Ink
  • 765
  • 2
  • 12
  • 38
  • you code is **asynchronous**, you need to move `console.log(pdfListPath);` just after the **for loop** inside the handler function – Olivier Boissé Aug 23 '17 at 13:01
  • TL;DR, `console.log(pdfList)` happens before the inner functions get called asynchronously. The real values are only available inside those inner functions (or use Promises and/or `async` functions) – Madara's Ghost Aug 23 '17 at 13:01
  • `function listDir(path, successHandler, errorHandler){ window.resolveLocalFileSystemURL(path, fileSystem => fileSystem.createReader().readEntries(successHandler, errorHandler), errorHandler) }` or better, you check out Promises; avoids callback hell in your code. – Thomas Aug 23 '17 at 13:07

1 Answers1

3

your for loop is wrong you need to change

for (var i = 0; i == entries.length; i++) {
    pdfListPath.push(entries[i]);
};  

to

for (var i = 0; i < entries.length; i++) {
    pdfListPath.push(entries[i]);
};  

(not 100% sure, maybe it's even <= you better check i and entries.length)

caramba
  • 21,963
  • 19
  • 86
  • 127