编程语言
首页 > 编程语言> > javascript – Node.js中For循环中的async.waterfall

javascript – Node.js中For循环中的async.waterfall

作者:互联网

在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

解决方法:

你可以像这样使用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");
});

标签:javascript,node-js,async-js
来源: https://codeday.me/bug/20190716/1476056.html