Nodejs异步系列 - 将参数传递给下一个回调

时间:2014-03-15 13:43:07

标签: node.js

当您使用异步模块时,如何将前一个回调中的参数传递给下一个?

以下是github上文档的一个例子

async.series({
    one: function(callback){
        setTimeout(function(){
            callback(null, 1);
        }, 200);
    },
    two: function(callback){
        setTimeout(function(){
            callback(null, 2);
        }, 100);
    }
},
function(err, results) {
    // results is now equal to: {one: 1, two: 2}
});

3 个答案:

答案 0 :(得分:84)

您可以将异步函数与异步模块的waterfall函数链接在一起。这允许你说,"首先做x,然后将结果传递给函数y,并将结果传递给z。"复制自[docs] [1]:

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'    
});

您并不需要异步模块来完成此任务;此功能旨在使代码更易于阅读。如果您不想使用异步模块,您可以随时使用传统的回调。

答案 1 :(得分:16)

另一种选择是使用async.auto。使用async auto,您可以指定任务的依赖关系数据,async将在能够时开始运行它。 README.md中有一个很好的例子,但这里大致是你上面的系列:

async.auto({
    one: function(callback){
        setTimeout(function(){
            callback(null, 1);
        }, 200);
    }, 
    // If two does not depend on one, then you can remove the 'one' string
    //   from the array and they will run asynchronously (good for "parallel" IO tasks)
    two: ['one', function(callback, results){
        setTimeout(function(){
            callback(null, 2);
        }, 100);
    }],
    // Final depends on both 'one' and 'two' being completed and their results
    final: ['one', 'two',function(err, results) {
    // results is now equal to: {one: 1, two: 2}
    }];
});

答案 2 :(得分:9)

我花了很多时间来解决这个问题,因为我遇到了类似的情况。我尝试了async.seriesasync.waterfall

<强> async.series 使用变量在回调函数之间共享。我不确定这是否是最好的方法。我必须赞扬Sebastian关于async的精彩文章。

var async1 = require('async');

exports.asyncSeries1 = function (req, res, callback) {

    var sharedData = "Data from : ";
    async1.series([
            // First function
            function(callback) {
                sharedData = "First Callback";
                callback();
            },
            // Second function
            function(callback){
                console.log(sharedData);
                sharedData = "Second Callback";
                callback();
            }
        ],
        // Final callback 
        function(err) {
            console.log(sharedData);
            if (err) {
                callback();
            }
            callback();
        }
    );
};

async.waterfall :我尝试使用async.apply使用另一个回调函数。这是帮助我解决问题的代码片段。 `

var async2 = require('async')

exports.asyncWaterfall1 = function (arg1, arg2, cb) {
    async2.waterfall([
        // async.apply
        async2.apply(assignVariables, arg1, arg2),
        // First callback
        function(arg1, arg2, callback){
            console.log(arg1);
            console.log(arg2);
            arg1 = 5;
            arg2 = 6;
            callback(null, arg1, arg2);
        },
        // Second callback
        function(arg1, arg2, callback){
          // arg1 now equals 'one' and arg2 now equals 'two'
            console.log(arg1);
            console.log(arg2);
            arg1 = 7;
            arg2 = 8;
            callback(null, arg1, arg2);
        }
    ], 
    function (err, arg1, arg2) {
        console.log(arg1);
        console.log(arg2);  
    });
};

// Method to assign variables
function assignVariables(arg1, arg2, callback) {
    console.log(arg1);
    console.log(arg2);
    arg1 = 3;
    arg2 = 4;
    callback(null, arg1, arg2);
};

PS Credit