Why does the async.map function work with the fs.stat built-in function?

async.map(['file1','file2','file3'], fs.stat, function(err, results){ // results is now an array of stats for each file }); 

According to the documentation , the second argument:

iterator (element, callback) - a function applied to each element in an array.

Fine

The iterator is given a callback (err, transformed), which should be called after its completion with an error (which may be zero) and the transformed element.

I think fs.stat not consistent with this, and I would say that this should not work.

It should be something like:

 async.map(['file1','file2','file3'], function (file, complete) { fs.stat(file, function (err, stat) { complete(err, stat) }); }, function(err, results){ // results is now an array of stats for each file } ); 
+2
source share
2 answers

fs.stat takes two parameters, the first is a file, the second is a callback, which by condition node takes two parameters, an error and file statistics:

 fs.stat(path, callback) 

which can be seen as

 fs.stat(path, function(err, stats){ // ... }); 

That's why it works, fs.stat is called, passing exactly what it needs.

Additional information: http://nodejs.org/api/fs.html#fs_fs_stat_path_callback

+6
source

From the documentation at http://nodejs.org/api/fs.html#fs_fs_stat_path_callback

fs.stat (path, callback)

Asynchronous stat (2). The callback receives two arguments (err, stats), where stats is the fs.Stats object. See the fs.Stats section below for more information.

Since fs.stat callback returns (err, stats), the following works fine

 async.map(['file1','file2','file3'], fs.stat, function(err, results){ // results is now an array of stats for each file }); 

To do the same, pass a function that with the appropriate callback

 var async = require('async') var inspect = require('eyespect').inspector(); function custom(param, callback) { var result = 'foo result' var err = null callback(err, result) } var items = ['item1', 'item2'] async.map(items, custom, function (err, results) { inspect(results, 'results') }) 
+1
source

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


All Articles