Why async.map function works with the native fs.stat function?

冷暖自知 提交于 2019-12-23 23:13:39

问题


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

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/16445649/why-async-map-function-works-with-the-native-fs-stat-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!