Search code examples
node.jsnode-async

node.async parallel : can we create dynamic texts to denote tasks?


Inside node async methods, we define tasks as "one" or "two" like in the example below. Is there a way to make that text dynamic ?

    var async = require("async");
    async.parallel({
        one: function(callback){
            setTimeout(function(){
                callback(null, 1);
            }, 200);
        },
        two: function(callback){
            setTimeout(function(){
                callback(null, 2);
            }, 100);
        }
    },
    function(err, results) {
        console.log(results); // results is now equals to: {one: 1, two: 2} 
    });

Solution

  • I agree with @Castaglia that you would probably benefit by providing more detail about what you are trying to do. That said, I will simply answer the question as stated.

    Yes, it is possible to compute the keys of the object dynamically. This applies to any object, not just the one you pass to async.parallel(). Perhaps the most elegant solution available in Node is to utilize a new ES2015 feature: computed property names.

    'use strict';
    
    const async = require('async');
    
    function dynmaicAsync(fnOne, fnTwo) {
      async.parallel({
        [fnOne](callback) { ... },
        [fnTwo](callback) { ... }
      },
      (err, results) => console.log(results));
    }
    
    dynmaicAsync('un', 'deux');
    // { un: 1, deux: 2}
    

    The example above also uses the ES2015 shorthand method definition syntax, which spares us from having to use the function keyword for method definitions on object literals.

    Alternatively, if you don't want to use these ES2015 features, you can just do something like this:

    'use strict';
    
    var async = require('async');
    
    function dynmaicAsync(fnOne, fnTwo) {
      var fns = {};
      fns[fnOne] = function { ... };
      fns[fnTwo] = function { ... };
      async.parallel(fns, function(err, results) { ... });
    }