node.js异步系列函数的参数

时间:2014-01-22 16:07:32

标签: javascript node.js async.js

我需要执行以下代码:

function taskFirst(k, v) {
    console.log(k, v);
}

function taskSecond(k, v) {
    console.log(k, v);
}

function run() {
    var g1 = "Something";
    var g2 = "Something";
    var g3 = "Something";
    var g4 = "Something";

    async.series(
        [
            taskFirst(g1, g2),
            taskSecond(g3, g4)
        ],
        function(error, result){

        }
    );
}

传递自定义变量和async.js回调函数的正确方法是什么?

4 个答案:

答案 0 :(得分:20)

你可以这样做:

function taskFirst(k, v, callback) {
    console.log(k, v);

    // Do some async operation
    if (error) {
        callback(error);
    } else {
        callback(null, result);
    }
}

function taskSecond(k, v, callback) {
    console.log(k, v);

    // Do some async operation
    if (error) {
        callback(error);
    } else {
        callback(null, result);
    }
}

function run() {
    var g1 = "Something";
    var g2 = "Something";
    var g3 = "Something";
    var g4 = "Something";

        async.series(
            [
                // Here we need to call next so that async can execute the next function.
                // if an error (first parameter is not null) is passed to next, it will directly go to the final callback
                function (next) {
                    taskFirst(g1, g2, next);
                },
                // runs this only if taskFirst finished without an error
                function (next) {
                    taskSecond(g3, g4, next);    
                }
            ],
            function(error, result){

            }
        );
}

答案 1 :(得分:2)

可以如下

function taskFirst(k, v) {
    console.log(k, v);
}

function taskSecond(k, v) {
    console.log(k, v);
}

async.series([
    function(callback) { 
        callback(null, taskFirst(g1, g2));
    },
    function(callback) { 
        callback(null, taskFirst(g3, g4));
    }
],function(error, result){

});

答案 2 :(得分:2)

对async的github问题的这个答案对我来说非常有用。 https://github.com/caolan/async/issues/241#issuecomment-14013467

对你来说就像是:

var taskFirst = function (k, v) {
   return function(callback){
      console.log(k, v);
      callback();
   }
};

答案 3 :(得分:1)

更好的方式。

const a1 = (a, callback) => {
    console.log(a, 'a1')
    callback()
}
const a2 = (a, callback) => {
    console.log(a, 'a2')
    callback()
}

const run = () => {
    async.series([
        a1.bind(null, 'asd'),
        a2.bind(null, 'asd2')
    ], () => {
        console.log('finish')
    })
}
run()