Using an asynchronous module to trigger a callback after viewing all files

I use the caolan 'async' module to open an array of file names (in this case, the names of the template files).

In the documentation, I use async.forEach () , so I can start the callback after all operations are complete.

A simple test case:

var async = require('async') var fs = require('fs') file_names = ['one','two','three'] // all these files actually exist async.forEach(file_names, function(file_name) { console.log(file_name) fs.readFile(file_name, function(error, data) { if ( error) { console.log('oh no file missing') return error } else { console.log('woo '+file_name+' found') } }) }, function(error) { if ( error) { console.log('oh no errors!') } else { console.log('YAAAAAAY') } } ) 

The output is as follows:

 one two three woo one found woo two found woo three found 

Ie it seems that the last callback is not working. What do I need to do to make the final callback fire?

+4
source share
2 answers

A function that runs in all elements must have a callback and pass its results to the callback. See below (I also split file_name for better readability):

 var async = require('async') var fs = require('fs') var fileNames= ['one','two','three'] // This callback was missing in the question. var readAFile = function(fileName, callback) { console.log(fileName) fs.readFile(fileName, function(error, data) { if ( error) { console.log('oh no file missing') return callback(error) } else { console.log('woo '+fileName+' found') return callback() } }) } async.forEach(fileNames, readAFile, function(error) { if ( error) { console.log('oh no errors!') } else { console.log('YAAAAAAY') } }) 

Return:

 one two three woo one found woo two found woo three found YAAAAAAY 
+9
source

This is the best way to do this, in my opinion. The result parameter will have an array of strings containing the file data, and all files will be counted in parallel.

 var async = require('async') fs = require('fs'); async.map(['one','two','three'], function(fname,cb) { fs.readFile(fname, {encoding:'utf8'}, cb); }, function(err,results) { console.log(err ? err : results); }); 
+1
source

Source: https://habr.com/ru/post/1398669/


All Articles