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

Asynchronous file reading, cannot make function finish before returning

I am trying to read all files in folder, check if it has featured: true prop, increase the counter if it does and then throw error if there is more than 1 such file. But for some reason, my code doesn’t wait and simply jumps to last section, this is the output

this should be last
Inside item, looking for featured prop
Inside item, looking for featured prop

My code:

const fs = require('fs');
const findInDir = require('./utils/findInDir');

(async () => {
  const dir = './public/page-data/blog';
  const fileRegex = /.*/;
  const allFiles = findInDir(dir, fileRegex);
  let result = 0;

  await allFiles.map(file => {
    fs.readFile(file, 'utf8', (err, data) => {
      const obj = JSON.parse(data);

      if (obj.result.pageContext.featured === true) {
        console.log('Inside item, looking for featured prop');
        result += 1;
      }
    });
  });

  console.log('this should be last');

  if (result > 1) {
    throw new Error('There are multiple featured blog posts, please fix.');
  }
})();

Need some help understanding what am I doing wrong.

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

>Solution :

You need to use the non-callback version of fs.readFile in order to actually await reading the file. Also using .map does not make a lot of sense as you’re not actually mapping something, so simply use a for .. of loop:

for (const file of allFiles){
 try {
   const data = await fs.promises.readFile(file);
   // ...
 } catch(err) {
   // handle error
 }
}

console.log('this should be last');
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