javascript - Async.map - 让它忽略错误,并处理整个列表

标签 javascript arrays node.js asynchronous

我必须用 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

我想要的是它不应该立即调用带有错误的回调,而是等待它处理整个列表,无论如何它都会处理,并且只然后调用回调

这可能吗?或者是否有以这种方式运行的 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/

相关文章:

javascript - NodeJS 的图像下载问题

javascript - Ember数据加载路线时出错: TypeError: undefined is not a function

javascript - 事件目标的问题

Node : get css file with html render

php - 从 Laravel 集合转换数组

c++ - 指针声明基础(多维数组指针赋值)

javascript - 如何检查Nightmare JS是否在 Debug模式下运行

javascript - 从 JS 中的另一个脚本获取函数

javascript - 如何在 Jquery Mobile 1.4.5 中刷新新的 Div 内容

arrays - Arduino Sketch - 头文件中的对象不包含任何值