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?

Answers:

Answer

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.

Answer

Instead you can use async.apply too

async.parallel(
[
  async.apply(negative, -1), //callback is automatically passed to the function
  async.apply(positive, 3)
],
(error, results) => {
console.log(error, results);
})

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.