Why async.map function works with the native fs.st

2019-07-20 19:04发布

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
    }
);

2条回答
男人必须洒脱
2楼-- · 2019-07-20 19:34

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')
})
查看更多
爷、活的狠高调
3楼-- · 2019-07-20 19:37

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

查看更多
登录 后发表回答