[英]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.