Async.apply inside async.waterfall

I have the following code snippet

async.waterfall([ // Read directory async.apply(fs.readdir, '../testdata'), // Load data from each file function(files, callback) { async.each(files, loadDataFromFile, callback); } ], function(err) { if (err) { api.logger.error('Error while inserting test data', err); } next(); }); 

Is there any way to replace this part:

 function(files, callback) { async.each(files, loadDataFromFile, callback); } 

using just a function? As I said above, using async.apply() , I replaced this:

 function(callback) { fs.readdir('../testdata', callback); } 

I know that I can create my own helper function to do this, or I can leave it like that, but I was wondering if there is a way to do this using only functions like .bind() or .apply() .

I thought about using .bind() then .apply() , but this will result in a function(loadDataFromFile, files, callback) , which is not suitable.

+1
source share
1 answer

I was wondering if there is a way to do this using only functions like .bind () or .apply ().

Do not use only native functions or only those from async . As you noticed, you need to flip to execute each function. Some partial application implementations (such as Underscore) allow intermediate arguments, but you need to explicitly include them.

Example with lodash partialRight :

 async.waterfall([ _.partial(fs.readdir, '../testdata'), // Read directory _.partialRight(async.each, loadDataFromFile), // Load data from each file ], function(err) { if (err) api.logger.error('Error while inserting test data', err); next(); }); 

You might need a bind method for the right context, though, like fs.readdir.bind(fs, '../testdata') .

+5
source

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


All Articles