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

标签 javascript node.js async.js

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

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) {...}
);

最佳答案

您可以改用 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 () {...}
);

关于javascript - nodejs 异步 : How to use a loop containing an asynchronous call within an "async.series" function block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48166469/

相关文章:

javascript - 如何获取动态创建元素的字符串表示

javascript - 方括号前有分号

javascript - ExpressJS 和 Cookie - 无法获取 express-cookie 来初始化 Cookie

node.js - 如何使用回调等待两个查询异步 Node

node.js 嵌套 async.eachSeries

javascript - Node.js 可以在 Chrome 中使用其 native 客户端运行客户端(即将发布)

javascript - 输入填充文本区域 - Javascript

javascript - 是否可以重新排序 node.js 事件循环?

node.js - 在 MEAN 堆栈中,如何进行一次性 MongoDB 索引?

javascript - async array.map() 和 async npm 包之间的区别