async.waterfall 在 Node.js 的 For 循环中

async.waterfall in a For Loop in Node.js

for 循环中使用 async.waterfall 时,似乎 for 循环在嵌套的 async.waterfall 完成其所有步骤之前进行迭代。如何避免这种情况?

for(var i = 0; i < users.length; i++ ) {

    console.log(i)

    async.waterfall([
        function(callback) {
            callback(null, 'one', 'two');
        },
        function(arg1, arg2, callback) {
          // arg1 now equals 'one' and arg2 now equals 'two'
            callback(null, 'three');
        },
        function(arg1, callback) {
            // arg1 now equals 'three'
            callback(null, 'done');
        }
    ], function (err, result) {
        // result now equals 'done'
        console.log('done')
    });


}

输出

0
1
2
3
4
done
done
done
done
done

期望输出

0
done
1
done
2
done
3
done
4
done

您需要应用递归模式。我的建议是这样的

function foo(properties, callback){
/*Initialize inputs w/ useful defaults.  Using a properties object simply because it looks nicer, you can use individual values if you'd like.*/
        properties.start = properties.start || 0;
        properties.end = properties.end || 10; //or any default length
        properties.data = properties.data || [];

        async.waterfall([
          function(callback) {
        },
        function(arg1, arg2, callback) {
          /* arg1 now equals 'one' and arg2 now equals 'two' you can do something with that before continuing processing */
        },
        function(arg1, callback) {
            /* arg1 now equals 'three', you can do something with that before continuing processing */

        }
    ], function (err, result) {
        // result now equals 'done' 
        // now that we have fully processed one record, we need to either finish or recurse to the next element.  

     if(properties.index >= properties.end){
       callback();
     }
     else{
       properties.index++;
       foo(properties, callback);
     }

    })}

我已将回调传递给每个函数回调。如果你愿意,你可以选择以这种方式提前结束递归,或者你可以在那个地方做你想做的任何其他事情。这类似于我最近提出的一个问题: 也有一些其他有趣的问题解决方案。

你可以像这样使用 async 的 forEachLimit

var async = require("async")
var users = []; // Initialize user array or get it from DB

async.forEachLimit(users, 1, function(user, userCallback){

    async.waterfall([
        function(callback) {
            callback(null, 'one', 'two');
        },
        function(arg1, arg2, callback) {
            // arg1 now equals 'one' and arg2 now equals 'two'
            callback(null, 'three');
        },
        function(arg1, callback) {
            // arg1 now equals 'three'
            callback(null, 'done');
        }
    ], function (err, result) {
        // result now equals 'done'
        console.log('done')
        userCallback();
    });


}, function(err){
    console.log("User For Loop Completed");
});