gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:28:04 27 4
gpt4 key购买 nike

在使用基于 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com