0

Ionic app written in typescript:

 let files: any[] = [];
 files =this.getFiles("wildlife");
 console.log("files:", files);
  this.render(files); 

this output says enter image description here

which is strange, cause although there are 50 items there but it shows Array(0). Problem is when i pass this array in function:

  render( files) 
    {
     files.forEach(item => {
    console.log(item) <- does not exist

    });
    }

Array is empty. Why is that ? Is there other way to pass the array and loop through its objects ?

EDIT:

getFiles(folder) {
    let files: any[] = [];

    this.file.listDir(this.file.applicationDirectory, 'www/assets/' + folder)
      .then((items) => {
        // console.log(items);

        items.forEach(item => {
          files.push({
            filename: item.name,
            name: this.getName( item.name)
          });
        });
      })
      .catch(err =>
        console.log("error: ", err));

    return files;
  }
Jalle
  • 1,566
  • 5
  • 22
  • 42
  • you can't use `await` without `async` wrap your code in function mark the function async – ricky Jan 10 '20 at 09:57
  • 2
    What goes `getFiles` look like? – Dan Gamble Jan 10 '20 at 09:57
  • I guess you are trying to log them in render function before they are actually there. You are maybe not using async await as you shoud. Could you post more of your code, in order for us to see bigger picture. – Lazar Nikolic Jan 10 '20 at 09:58
  • please ignore async/await keyword. Ive tried with and w/out that – Jalle Jan 10 '20 at 09:59
  • 3
    I suspect you are [not properly returning some async response](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) and you are [looking at this in the browser console which is lazy about evaluating objects](https://stackoverflow.com/questions/10566290/chrome-and-firefox-javascript-console-different-return-value) so *when you log* `files` it's an empty array but *when you expand it* (different point in time), it's now populated. The code here is not enough to say how exactly to fix it but check my first link. – VLAZ Jan 10 '20 at 10:08
  • I agree with @VLAZ. Please share more of your code – Lazar Nikolic Jan 10 '20 at 10:09
  • post updated now – Jalle Jan 10 '20 at 10:23
  • @Jalle: you're returning `files` before `listDir` has called your callback. So it will be empty immediately after the call and populated at some later time. – Joachim Sauer Jan 10 '20 at 10:32

1 Answers1

0

You need to call your getFiles function as asynchronous function.

let files: any[] = [];
 this.getFiles("wildlife")
   .then(res => {
     files = res;
     console.log("files:", files);
     this.render(files);
 }); 
Ashish Modi
  • 7,529
  • 2
  • 20
  • 35