0

I have an objective to map through a list of json files, and map them into objects and return them in node.js, so far I have the following code:


function getDirFiles(dataFolder) {
  return new Promise((resolve, reject) => {
    let fileNames = [];
    fs.readdir(dataFolder, (err, files) => {
      if (err) {
        console.log(err);
        reject(err);
      } else {
        files.forEach(file => {
          fileNames.push(file);
        });

        resolve(fileNames);

      }
    });
  });
}

let data = []
getDirFiles(dataFolder).then(files =>{
    files.forEach(async file =>{
        const fileName = __dirname + '/parsed_json_data' + '/' + file
       await fs.readFile(fileName , 'utf8', async function(err, data){
            if(err) throw err;
            data = await JSON.parse(data);
        })
    })
})


console.log(data) //return empty array like it was initialized

So first I return a promise, and call a .then() to resolve the function, but since, the next operation is also async, I want to await, this operation, before the code proceeds. How can this be achieved, so that I can return the json from all the files?

DAme
  • 697
  • 8
  • 21
Kristoffer Tølbøll
  • 3,157
  • 5
  • 34
  • 69
  • `await fs.readFile` isn't needed as `readFile()` doesn't return a promise (or any value even) to `await`. Also forEach doesn't wait for async functions your callback isn't going to wait for each call to finish. Also you used a parameter variable named `data` which makes it so you are not setting the outer scope `data` in your readFile callback – Patrick Evans Nov 19 '19 at 14:20
  • Also JSON.parse returns the value, not a promise – David Vicente Nov 19 '19 at 14:22
  • Okay good points, i fixed all that, so that it push a new jsonelement onto the array, yet it still logs an empty array... – Kristoffer Tølbøll Nov 19 '19 at 14:24
  • did you also change the parameter name? Having `function(err, data)` makes it so you can't access the outer `data`. Also you can't log it outside of the then()'s as its all async code. Using await does not stop execution outside of async functions – Patrick Evans Nov 19 '19 at 14:26

0 Answers0