【发布时间】:2017-01-28 11:04:31
【问题描述】:
我试图理解 async each(coll, iteratee, callback) 函数来为数组的每个项目并行执行一个函数。从异步文档中,我了解到回调只会执行一次(当迭代函数将为数组的每个项目执行时)。
并且在iteratee函数出错的情况下,调用callback('some error message')会立即调用带有错误信息的回调函数。
以下是每个函数的异步文档中的示例
每个(coll,iteratee,回调)
// 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');
}
});
我无法理解的是,不带参数调用 callback() 是做什么的,当 iteratee 函数中没有错误时,我们不带参数调用 callback() 对我来说看起来很奇怪。如果没有错误,调用callback() or callback(null) 会做什么。
我们不能只删除那些callback() or callback(null),而实际上我们的意思是只调用一次回调(当对数组的所有元素执行 iteratee 函数时)而不是对数组的每个项目。
【问题讨论】:
标签: javascript asynchronous async.js