Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
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.

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

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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.

}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!