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

As per documentation, the second argument is:

iterator(item, callback) - A function to apply to each item in the array.

Fine.

The iterator is passed a callback(err, transformed) which must be called once it has completed with an error (which can be null) and a transformed item.

I think thatfs.stat does not conform to this and I would say that this shouldn't 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
    }
);
Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
gremo
  • 47,186
  • 75
  • 257
  • 421
  • "Afaik fs.stat dos not call `callback(err, stat)`" What do you mean by that? That's exactly what you're doing in your code. – SLaks May 08 '13 at 16:31
  • @SLaks I mean why passing fs.stat works with async.map. My example is how I would implement the same behavior. – gremo May 08 '13 at 16:33
  • That sentence doesn't make sense. Your code does exactly what you claim doesn't work. – SLaks May 08 '13 at 16:37
  • 1
    He's asking why the first example works. In the second he wrote how he would have coded it (because he's confused about why the first works). – Alberto Zaccagni May 08 '13 at 16:39

2 Answers2

6

fs.stat accepts two parameters, the first is the file, the second is the callback, which by node convention accepts two parameters, an error and the stats of the file:

fs.stat(path, callback)

which could be seen as

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

This is why it works, fs.stat is called by passing exactly what it needs.

More info: http://nodejs.org/api/fs.html#fs_fs_stat_path_callback

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
1

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

fs.stat(path, callback)

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

Since the 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 yourself pass a function which 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')
})
Community
  • 1
  • 1
Noah
  • 33,851
  • 5
  • 37
  • 32