Async.map - 让它忽略错误,并处理整个列表
Async.map - make it ignore the error(s), and process the entire list
我必须用 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 main callback
(for the map
function) is immediately called with the error.
所以我得到
processing 1
[Error: 1]
processing 2
processing 3
processing 4
我想要的是 不应该 立即调用 callback
并出现错误,但要等到它处理整个列表,无论如何它都会处理,然后才调用 callback
.
这可能吗?或者是否有 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);
我有一个类似的问题,我的迭代器会向我的数组发送空值,所以我使用了 async.mapLimit
函数。
mapLimit(coll, limit, iteratee, callback)
参见:
https://caolan.github.io/async/docs.html
希望对您有所帮助。
我必须用 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
我想要的是 不应该 立即调用 callback
并出现错误,但要等到它处理整个列表,无论如何它都会处理,然后才调用 callback
.
这可能吗?或者是否有 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);
我有一个类似的问题,我的迭代器会向我的数组发送空值,所以我使用了 async.mapLimit
函数。
mapLimit(coll, limit, iteratee, callback)
参见:
https://caolan.github.io/async/docs.html
希望对您有所帮助。