Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to determine if a Javascript self-referencing loop completes

I have a situation where I need to read all the files in a directory and all its subdirectories. I wrote a basic function:

Although this is in React-Native, I’m not sure that matters (or maybe there is a react-native solution).

let fileList = [];

const readDir = async (dir) => {

  // This line simply reads the contents of a directory, creating an array of strings
  // of all the files and directories inside 'dir'.
  const items = await FileSystem.readDirectoryAsync(dir); 

  items.forEach(async (item) => {
    const f = await FileSystem.getInfoAsync(item); // Gets basic information about the item
    if (f.isDirectory === true) {
      readDir(f.uri); // f.uri is the location of the new directory to read
    } else {
      // runs if the item is a file
      console.log("f.uri: ", f.uri);
      fileList.push(f.uri); // A global variable
    }
  })
};

const parentDirectory = "parent_folder";
readDir(parentDirectory);

// Do more stuff here once all files have been read and added to 'fileList'

This seems to partially work as all the files in all the subdirectories are consoled out from inside the else {…} segment.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, how can I know the loop is complete so I can continue the script and use ‘fileList’?

>Solution :

Don’t use forEach with async they don’t work together and you can’t await the loop. Use a standard for .. of loop, which works nicely with async/await

const readDir = async (dir) => {
  const items = await FileSystem.readDirectoryAsync(dir);

  for (let item of items) {
    const f = await FileSystem.getInfoAsync(item); 
    if (f.isDirectory === true) {
      await readDir(f.uri); 
    } else {
      console.log("f.uri: ", f.uri);
      fileList.push(f.uri); 
    }
  }
}

And as readDir is async as well, you have of course either to await it also, or use then to continue once it is finished

async function foo() {
   const parentDirectory = "parent_folder";
   await readDir(parentDirectory);
   //do some other stuff once readdir is finished.
}

or

const parentDirectory = "parent_folder";
readDir(parentDirectory).then(_ => {
   //do some other stuff once readdir is finished.

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading