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:
- Promisify fs.readFile (by using, for example Bluebird)
- Mark the function as async
- Make a list of callbacks (my_list.map instead of forEach)
- "await Promise.all(myListOfCallbacks)"
- 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