[英]How do I define the callback in the Async library's “Each” function?
在Caolan的Async庫中,文檔說明了each
函數:
將函數iteratee並行應用於arr中的每個項目。 使用列表中的項目調用iteratee,並在完成時調用它。
給出了這個例子:
async.each(arr, iteraree, function(err){
//Do stuff
});
我的問題是如何定義“回調”,在這種情況下是iteraree
? 如何在完成后聲明要調用哪個回調函數?
如果你能夠將函數定義為參數我可以看到它工作,但你不能(即):
async.each(openFiles, function (item, function () {console.log("done")}), function(err){
//Do stuff
});
但是我如何定義該回調不是內聯的呢?
如果我做的事情
var iteraree = function (item, callback) {};
並且在iteraree
傳遞,我仍然沒有看到我能夠定義callback
行為的位置。
該iteratee函數沒有您認為的簽名。 它看起來像這樣:
async.each(openFiles, function (item, cb){
console.log(item);
cb();
}, function(err){
//Do stuff
});
它接收來自asynchronous.each()的每個項目和一個回調函數,當你完成你正在做的事情時必須調用它。 您不提供回調。
因此,如果您使用的是命名函數,它只是:
function foo (item, cb){
console.log(item);
cb();
}
async.each(openFiles, foo, function(err){
//Do stuff
});
我仍然沒有看到我能夠定義
callback
的行為。
你沒有。 callback
只是一個參數。 async.each
調用iteratee
並傳遞一個值用於callback
。 完成后調用 callback
是你的責任。 這讓async.each
知道它可以繼續下一次迭代。
function (item, function () {console.log("done")})
是無效的JavaScript btw。 您不能使用函數定義來代替參數。
以下是來自其文檔的示例的修改版本以及添加的注釋
//I personally prefer to define it as anonymous function, because it is easier to see that this function will be the one iterated
async.each(openFiles, function(file, callback) {
callback(); //this is just like calling the next item to iterate
}, then);
//this gets called after all the items are iterated or an error is raised
function then(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');
}
}
如您可以看到的以下代碼,它是一個內置函數,使我們能夠根據自定義限制拋出錯誤。 它的所有細節都由異步模塊控制,我們不應該覆蓋它。 它是一種這樣的功能:你需要使用它,你不需要定義它。
const async = require('async');
const array = [1, 2, 3, 4, 5];
const handleError = (err) => {
if (err) {
console.log(err);
return undefined;
}
}
async.each(array, (item, cb) => {
if (item > 2) {
cb('item is too big');
}
else {
console.log(item);
}
}, handleError);
控制台日志:
1
2
item is too big
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.