node-async不执行回调

时间:2017-03-09 04:03:23

标签: node.js async.js

守则

我尝试使用此程序包https://www.npmjs.com/package/async来实现系列&并行处理。

对于小案例,它很有效,但是当我尝试运行它时,我得到了一个意想不到的行为:

async.series([
    function(callback){
        console.log('one');
        callback();
    },
    function(callback){
        console.log('two');
        async.parallel([
            function(callback){
                console.log('two-one');
                callback();
            },
            function(callback){
                async.series([
                    function (callback){
                        console.log('two-two-one');
                        callback();
                    },
                    function (callback){
                        console.log('two-two-two');
                        callback();
                    }
                ]);
            }
        ], callback);
    },
    function(callback){
        console.log('three');
        callback();
    }
]);

预期结果

代码应该串联打印onetwotwo-onethree。但是,在打印two-one后,我想要并行打印two-two-onetwo-two-two

预期结果是:

one
two
two-one
two-two-one
two-two-two
three

one
two
two-one
two-two-two
two-two-one
three

真实结果

不幸的是,永远不会打印three

one
two
two-one
two-two-one
two-two-two

问题

我的代码/理解有问题吗?

感谢。

1 个答案:

答案 0 :(得分:1)

异步系列将最后一个参数作为函数来获取最终结果。

请将并行回调作为异步系列的第二个参数传递。

async.series([
    function(callback){
        console.log('one');
        callback();
    },
    function(callback){
        console.log('two');
        async.parallel([
            function(callback){
                console.log('two-one');
                callback();
            },
            function(callback){
                async.series([
                    function (callback){
                        console.log('two-two-one');
                        callback();
                    },
                    function (callback){
                        console.log('two-two-two');
                        callback();
                    }
                ],callback);// pass parallel callback to trace the outcome 
            }
        ], callback);
    },
    function(callback){
        console.log('three');
        callback();
    }
],console.log);// use console.lg to get the final outcome of series