我必须用 async 处理数组
var arr = [1,2,3,4];
Async.map(arr, iterator, callback);
我无法控制的 iterator
函数会为所有值抛出错误,例如 4
。
function iterator(val, cb) {
console.debug('processing', val);
if (val == 4) cb();
else cb(new Error(val));
}
异步会做的是
If
iterator
passes an error to his callback, the maincallback
(for themap
function) is immediately called with the error.
所以我明白了
processing 1
[Error: 1]
processing 2
processing 3
processing 4
我想要的是它不应该立即调用带有错误的回调
,而是等待它处理整个列表,无论如何它都会处理,并且只然后调用回调
。
这可能吗?或者是否有以这种方式运行的 Async.map 的替代方案?
最佳答案
If iterator passes an error to his callback, the main callback (for the map function) is immediately called with the error
https://github.com/caolan/async#map
您可以改为将空值传回回调而不是出错。
function iterator(cb, trans) {
try {
// something
cb(null, transformed);
}
catch (ex) {
// log the error perhaps
cb(null, null);
}
}
由于您无法控制迭代器,您可以围绕它编写一个包装器。
假设他们的迭代器叫做 their_iterator
。
function my_iterator(cb, trans) {
var my_cb = function(their_err, their_trans) {
if (their_err) {
// log error
cb(null, null);
}
else {
cb(null, their_trans);
}
}
their_iterator(my_cb, trans);
}
Async.map(arr, my_iterator, callback);
关于javascript - Async.map - 让它忽略错误,并处理整个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29598970/