node.js async series function's arguments

…衆ロ難τιáo~ 提交于 2019-12-04 18:09:17

问题


I need to do the code like following:

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){

        }
    );
}

What is the right way to pass custom variables and async.js callback function?


回答1:


You could do something like this:

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){

            }
        );
}



回答2:


It can be as follows

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){

});



回答3:


This answer to async's github issue has worked for me perfectly. https://github.com/caolan/async/issues/241#issuecomment-14013467

for you it would be something like:

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



回答4:


Better way.

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()


来源:https://stackoverflow.com/questions/21288014/node-js-async-series-functions-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!