【问题标题】:node-async doesn't execute callbacknode-async 不执行回调
【发布时间】:2017-03-09 14:07:53
【问题描述】:

守则

我尝试了这个包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

问题

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

谢谢。

【问题讨论】:

    标签: node.js async.js


    【解决方案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
    

    【讨论】:

    • 我只是用// pass parallel callback to trace the outcome评论改行。而且效果很好。刚才在 async.series 中有第二个参数,它似乎是无证的 :(。Thx btw
    • @Kundu 请对代码块使用 4 个空格的缩进,而不是反引号。
    • @AlexisTyler 很抱歉给您带来不便。我使用移动浏览器添加了答案。感谢您的编辑顺便说一句。
    猜你喜欢
    • 2017-09-15
    • 2020-04-13
    • 2017-08-12
    • 2023-04-10
    • 2018-03-27
    • 2020-11-19
    • 2021-06-11
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多