为什么async.map功能与本地fs.stat功能工作? [英] Why async.map function works with the native fs.stat function?

查看:148
本文介绍了为什么async.map功能与本地fs.stat功能工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  async.map(['文件1','文件2','file3的'],fs.stat,功能(错了,结果){
    //结果是现在的统计资料为每个文件的数组
});

根据文档,第二个参数是:


  

迭代器(项目,回调) - 该功能可应用到每个项目
  数组。


精细。


  

该迭代器传递一个回调(ERR,转化),必须
  一旦它已经与一个错误(其可以为空)完成调用和
  转化项目。


我觉得 fs.stat 不符合这一点,我会说,这不应该工作。

应该是这样的:

  async.map(['文件1','文件2','file3的'],
    功能(文件,完成){
        fs.stat(文件,函数(ERR,STAT){
            完整(ERR,STAT)
        });
    },功能(错了,结果){
        //结果是现在的统计资料为每个文件的数组
    }
);


解决方案

fs.stat 接受两个参数,第一个是文件,第二个是回调,这通过节点惯例接受两个参数,一个错误,该文件的数据:

  fs.stat(路径,回调)

它可以被看作是

  fs.stat(路径,函数(ERR,统计数据){
  // ...
});

这就是为什么它的工作原理, fs.stat 通过传递正是它需要调用。

更多信息:<一href=\"http://nodejs.org/api/fs.html#fs_fs_stat_path_callback\">http://nodejs.org/api/fs.html#fs_fs_stat_path_callback

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

解决方案

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

这篇关于为什么async.map功能与本地fs.stat功能工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆