集合(二) each - sanlex/async_chinese GitHub Wiki

each

each(coll,iteratee,callback)

iteratee使用coll中的每一个参数,并行的执行.如果在执行过程中发生错误,主回调立即被调用并抛出错误. 请注意,由于iteration是并行的,所以不能保证迭代函数按顺序完成.

别名:forEach

参数:

Name Type Description
coll Array/Iterable/Object 要迭代的集合
iteration AsyncFunction 对每个参数使用(item,callback)的形势调用,但是不会获得数组的索引.如果需要索引,请使用 eachOf
callbac function 所有的iteration完成或发生错误后回调,使用(err)的形势调用.

案例:

// assuming openFiles is an array of file names and saveFile is a function
// to save the modified contents of that file:

async.each(openFiles, saveFile, function(err){
  // if any of the saves produced an error, err would equal that error
});

// assuming openFiles is an array of file names
async.each(openFiles, function(file, callback) {

    // Perform operation on file here.
    console.log('Processing file ' + file);

    if( file.length > 32 ) {
      console.log('This file name is too long');
      callback('File name too long');
    } else {
      // Do work to process file here
      console.log('File processed');
      callback();
    }
}, function(err) {
    // if any of the file processing produced an error, err would equal that error
    if( err ) {
      // One of the iterations produced an error.
      // All processing will now stop.
      console.log('A file failed to process');
    } else {
      console.log('All files have been processed successfully');
    }
});

eachLimit

eachLimit(coll,limit,iteratee,callback)

和each一样,使用limit限制了一次运行异步操作的最大条数

别名:forEachLimit

eachOf

eachOf(coll,iteratee,callback)

和each一样,不过可以将coll中的,key(或index)作为第二个参数传递给iteration

别名: forEachOf

补充参数:

Name Type Description
iteratee AsyncFunction 对每个参数使用(item,key(value),callback)的形势调用

案例:

var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
var configs = {};

async.forEachOf(obj, function (value, key, callback) {
    fs.readFile(__dirname + value, "utf8", function (err, data) {
        if (err) return callback(err);
        try {
            configs[key] = JSON.parse(data);
        } catch (e) {
            return callback(e);
        }
        callback();
    });
}, function (err) {
    if (err) console.error(err.message);
    // configs is now a map of JSON data
    doSomethingWith(configs);
});

eachOfLimit

eachOfLimit(coll,limit,iteratee,callback)

和eachOf一样,通过limit限制并行的最大数.

eachOfSeries

eachOfSeries(coll, iteratee, callback)

与eachOf 按顺序一次只运行一个异步操作相同

别名: forEachOfSeries

eachSeries

eachSeries(coll, iteratee, callback)

与each 按顺序一次只执行一个异步操作相同

别名: forEachSeries

上一篇 集合(一) collections
下一篇 集合(三) every

⚠️ **GitHub.com Fallback** ⚠️