I find myself writing something like this a lot in my code, and I'm sure there's a standard library out there that makes this a lot simpler - hopefully a one liner. Essentially I want to write an async handler for an array, that does some async work per item in the array, and calls back regarding all work on the array either: (A) after every single item in the array was async handled successfully, or (B) if there was any error, exiting early if possible - BUT only such that the master callback is called precisely once.

我发现自己在我的代码中写了很多这样的东西,而且我确信那里有一个标准的库,这使得它更简单 - 希望是一个单行。本质上我想为数组编写一个异步处理程序,它为数组中的每个项目执行一些异步工作,并回调有关数组上的所有工作:(A)在数组中的每个项目成功执行异步处理之后,或者(B)如果有任何错误,尽可能早退出 - 但仅限于主回调被恰好调用一次。

Hoping for an answer that works for both browser and node:

希望找到适用于浏览器和节点的答案:

// @items - an array
// @cb - callback after all of `items` processed, taking an optional Error first argument
function doForEachAndCb(items, cb) {
  var exitEarly, tasksRemaining;
  if (!items || typeof items !== 'object' || !items.length) {
    cb();
    return;
  }

  tasksRemaining = items.length;
  exitEarly = false;

  function finishOneTask(err) {
    // finishOneTask() is no-op if previously called with an error passed.
    if (exitEarly) {
      return;
    }
    if (!!err) {
      exitEarly = true;
      cb(err);
      return;
    }
    tasksRemaining--;
    if (tasksRemaining === 0) {
      cb();
    }
  }

  items.map( (v) => {
    try {
      handleItemAsync(items[v], finishOneTask);
    } catch (err2) {
      finishOneTask(err2);
    }
  });
}

1 个解决方案

#1


0

Check out async#map():

查看async#map():

async.map(items, (item, callback) => {
  // do something async
  ...
  // when async operation has finished, call
  // the callback with the mapped value
  callback(null, value);
}, (err, mappedItems) => {
  ...
});

If you have no need to build an array of mapped values, you can use async#each instead.

如果您不需要构建映射值数组,则可以使用async#each。

Both async#map() and async#each() also have a sequential version, where each item is processed only after the previous processing step has completed (the "regular" versions process all items in parallel): async#mapSeries() and async#eachSeries().

async#map()和async#each()也都有顺序版本,其中每个项目仅在前一个处理步骤完成后处理(“常规”版本并行处理所有项目):async#mapSeries()和异步#eachSeries()。

更多相关文章

  1. 如何通过ajax将javascript数组传递给YII动作
  2. 在Javascript中将带有空格的字符串数组转换为小写,然后在Webkit中
  3. 返回指定时间段相同间隔数组
  4. JavaScript数组中的唯一计数,按计数排序
  5. Javascript sort()不适用于Chrome中超过10个对象的数组
  6. 获取JavaScript数组元素的最大长度
  7. 在项目之间共享ASP.NET MVC部分视图
  8. React:更新列表中的一个项目而不重新创建所有项目
  9. 对多维数组中的列进行排序

随机推荐

  1. MySQL 绿色版基本设置语句
  2. tp框架报“mysql_connect(): The mysql e
  3. mysql中binglog底层原理分析
  4. MySQL利用Navicat导出数据字典
  5. mysql故障---is not allowed to connect
  6. MYSQL导入导出命令详解
  7. windows安装mysql 遇到错误193的解决办法
  8. linux安装mysql、tomcat和jdk1.7、Androi
  9. 向数据库添加1的PHP Onclick事件(SQL)
  10. 在4个表上使用JOIN和GROUP BY进行复杂的S