Node.js中Async包的.each()方法中的回调函数
问题描述:
在Async包的文档中,each()
方法需要3个参数each(coll, iteratee, callback)
。我的问题不是关于第三个参数callback
,而是第二个参数iteratee
中的另一个“回调”函数。Node.js中Async包的.each()方法中的回调函数
它说iteratee
是一种类型AsyncFunction()
函数,它也需要一个callback
函数作为参数。以下是文档中提供的示例。
// 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');
}
});
在这个例子中,第二个参数function(file, callback)
应该是iteratee
功能。但是,我不明白callback
参数是在哪里定义的。在上面的例子中,它被称为callback('File name too long');
和callback('File name too long');
,但是这个函数究竟做了什么?通过直觉,当file
完成处理以通知这个事实时,可以调用该函数。但是在哪里我可以找到callback
函数的确切代码?
您会在'each'的实现中找到代码,它将函数传递给迭代器。但不要去寻找它 - 这是相当复杂的代码。是的,当iteratee完成时,'callback'应该被调用,结果或错误,并且调用它将触发async.each所做的任何下一步。 – Bergi
这个例子很糟糕,因为实际上没有异步事件发生。 – Bergi