在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