async.waterfall里面的async.each不行吗?

async.waterfall inside async.each doesn't work?

我正在尝试 运行 对一组项目进行 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() 而不是。