Saturday, 24 February 2018

javascript - Node.js wait for all files read in the loop



I am new to the javascript/node.js event driven paradigm.




I need to stop the for after forEach to make sure all files have been read and then I continue. How should I implement wait_for_all_files_read() in this context?



my_list.forEach(function(element) {
fs.readFile(element.file_path, function(err, data) {
if(err) throw err;
element.obj=JSON.parse(data);
});
});
wait_for_all_files_read(); <-----------
analyze(my_list)



Neither solution [1] or [2] work for me.


Answer



How I would do that:




  1. Promisify fs.readFile (by using, for example Bluebird)

  2. Mark the function as async

  3. Make a list of callbacks (my_list.map instead of forEach)


  4. "await Promise.all(myListOfCallbacks)"

  5. Next line after await will be executed after all the operations been finished



Something like that:





const {promisisfy} = require('util')
const fs = require('fs')

const readFile = promisify(fs.readFile)

const fileNames = getFilenamesArray();

async function executeMe() {
try {
const arrayWithFilesContent = await Promise.all(
fileNames.map(name => readFile(name))
);
return analyze(arrayWithFilesContent);

}
catch (err) {
handleError(err)
}
}

executeMe();





No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...