Saturday, February 24, 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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...