gpt4 book ai didi

javascript - async.each 中的 async.waterfall 不起作用?

转载 作者:搜寻专家 更新时间:2023-11-01 00:30:38 27 4
gpt4 key购买 nike

我正在尝试对一组项目运行 async.each。

对于每个项目,我想运行一个 async.waterfall。请参阅下面的代码。

var ids = [1, 2];

async.each(ids,

function (id, callback) {

console.log('running waterfall...');

async.waterfall([

function (next) {

console.log('running waterfall function 1...');

next();
},

function (next) {

console.log('running waterfall function 2...');

next();
}],

function (err) {

if (err) {
console.error(err);
}
else {
console.log('waterfall completed successfully!');
}

callback();
});
},

function (err) {

if (err) {
console.error(err);
}
else {
console.log('each completed successfully!');
}

});

return;

此代码的输出如下所示:

running waterfall...
running waterfall function 1...
running waterfall...
running waterfall function 1...
running waterfall function 2...
running waterfall function 2...
waterfall completed successfully!
waterfall completed successfully!
each completed successfully!

但我的意图是,我的理解是输出应该是这样的:

running waterfall...
running waterfall function 1...
running waterfall function 2...
waterfall completed successfully!
running waterfall...
running waterfall function 1...
running waterfall function 2...
waterfall completed successfully!
each completed successfully!

我一直在查看代码,但我不知道哪里出了问题,有人知道我的代码或我对异步方法应该做什么的期望是否不正确吗?

谢谢!

最佳答案

async.each() 尝试并行运行循环的所有迭代,因此所有迭代可能同时进行,并以不确定的顺序完成。您可以在 doc for .each() 中清楚地看到这一点。 :

Applies the function iteratee to each item in arr, 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.

Note, that since this function applies iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order.

因此,这解释了为什么您的 .waterfall() 迭代同时进行而不是连续运行。

如果你想一个接一个地运行它们,那么你应该使用async.eachSeries() 代替。

关于javascript - async.each 中的 async.waterfall 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36025014/

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