2017-12-02 240 views
0

在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函数的确切代码?

+0

您会在'each'的实现中找到代码,它将函数传递给迭代器。但不要去寻找它 - 这是相当复杂的代码。是的,当iteratee完成时,'callback'应该被调用,结果或错误,并且调用它将触发async.each所做的任何下一步。 – Bergi

+0

这个例子很糟糕,因为实际上没有异步事件发生。 – Bergi

回答

0

我相信你可以通过iteratorCallback函数找到回调定义here

+0

看起来它和第三个参数'callback'有关(就像它的一种包装功能)。我没有深入研究'onlyOnce()'函数,但假设如果在执行'iteratee'过程中发生任何错误,'callback'将被调用'error'参数。否则,当所有进程完成这个工作时,'callback'函数最终将被调用'null'参数? – jaedong

+0

是的。在你发布的例子中,'iteratee'调用的'callback'指的是提供给async.each的最后一个参数 - 'function(err)' – rgon