Node.js中For循环中的async.waterfall [英] async.waterfall in a For Loop in Node.js

查看:207
本文介绍了Node.js中For循环中的async.waterfall的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When using async.waterfall within a for loop, it appears that the for loop iterates before the nested async.waterfall finishes all its steps. How can this be avoided?

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

You can use like this with async's 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");
});

这篇关于Node.js中For循环中的async.waterfall的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆