Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to async.parallel in node.js

I am attempting to create a minimal example where I can accomplish what I describe above. For this purpose, here is my attempt for a minimal example, where in the end I would like to see in the output

negative of 1 is -1

plus one of 2 is 3

Here is my code.

var async = require('async');
var i, args = [1, 2];
var names = ["negative", "plusOne"];

var funcArray = [
    function negative(number, callback) {
        var neg = 0 - number;
        console.log("negative of " + number + " is " + neg);
        callback(null, neg);
    },
    function plusOne(number, callback) {
        setTimeout(function(number, callback) {
            var onemore = number + 1
            console.log("plus one of " + number + " is " + onemore);
            callback(null, onemore);
        }, 3000);
    }];

var funcCalls = {};
for (i = 0; i < 2; i++) {
    funcCalls[names[i]] = function() {
        funcArray[i].apply(this, args[i]);
    };
}

async.parallel(funcCalls, function(error, results) {
    console.log("Parallel ended with error " + error);
    console.log("Results: " + JSON.stringify(results));
});

Note that I am passing a named object to async.parallel as well. Passing an array (and forgetting entirely about the names) would also work as an answer for me, but I am more interested in passing such an object.

Any ideas on achieving my goal?

like image 705
MightyMouse Avatar asked Oct 17 '14 18:10

MightyMouse


1 Answers

Why not to bind the initial values? Then you would have something like this:

async.parallel([
    negative.bind(null, -1),
    plusOne.bind(null, 3)
], function(err, res) {
    console.log(err, res);
});

Of course you could generate the list with various parameters. This was just to give an idea of a simplified approach.

like image 186
Juho Vepsäläinen Avatar answered Sep 28 '22 23:09

Juho Vepsäläinen