nodejs-async:如何在 "async.series" 函数块中使用包含异步调用的循环

nodejs-async: How to use a loop containing an asynchronous call within an "async.series" function block

在使用基于 async.series 的设计时,我必须在功能块中使用循环,如下所示:

var someFile = filePath;
async.series([
    function(cb) {
         _.forEach (
               someDataList,
               function (item) {
                   //call that executes out of sync
                   writeToFile(someFile,item)
                   //how to provide callback here
                   cb(); //<- is this correct - won't this take control out of this block in the very first loop iteration?
               }
         );
    }
],
//callback function
function (err) {...}
);

要探索有关异步的更多信息,您可以使用他们的方法 each

Applies the function iteratee to each item in coll, in parallel. The iteratee is called with an item from the list, and a callback for when it has finished. If the iteratee passes an error to its callback, the main callback (for the each function) is immediately called with the error.

您的代码可以转换为:

var someFile = filePath;
async.series([
    function (cb) {
      async.each(someDataList, function (item, callback) {
        //call that executes out of sync
        writeToFile(someFile,item)

        // Execute internal callback for `async.each`
        callback()
      }, function (error) {
        if (error) {
          cb(error)
        } else {
          cb()
        }
      })
    }
  ],
//callback function
  function (err) {...
  }
);

但是,当然,您需要查看您的 writeToFile 功能。 如果它是 sync 你需要将它包装在 try {} catch(e){} 构造和 运行 内部 callback() 中,在 catch 部分有错误 callback(error)

您可以改用 forEachSeries。

var someFile = filePath;
async.forEachSeries(someDataList, function(item, cb) {
   writeToFile(someFile, item)
   cb();
},
//callback function
function () {...}
);

评论后更新:

不幸的是,无法在 forEachSeries 中获取迭代对象的索引。如果你想要 iteratee 的索引,你可以使用 eachOfSeries

var someFile = filePath;
async.eachOfSeries(someDataList, function(value, key, callback) {
    //Do something with key
    writeToFile(someFile, item)
    callback();
}, //callback function
function () {...}
);