简体   繁体   中英

How to execute node js functions one after another which dynamically listed using their names in a string array

I need to achieve following in my Node.js program.

  1. How create a function array from their names provided in strings?
  2. How to execute those functions one after another. Not asynchronously.
  3. How to pass parameters for those functions.

Suggest me a better approach to achieve this or code snippet somewhere already implemented this.

Step 1. Define the list

var functions = ["foo", "bar", "baz"];

Step 2. Iterate the list

We iterate over the function list and call the __call function.

functions.forEach(function(f){
   __call(f);
});

Step 3. Call the function

This step is dependent on framework. If you're using node, you have to use the global object. If you're using a browser (HTML) you have to use the window object.

For the former, use:

__call = function(f) { 
    var args = []; 
    for(var i = 1; i<arguments.length; i++){
        args.push(arguments[i])
    }; 
    console.log(args);
    global[f].apply(null, args); 
};

For the latter, use:

 __call = function(f) { 
    var args = []; 
    for(var i = 1; i<arguments.length; i++){
        args.push(arguments[i])
    }; 
    console.log(args);
    window[f].apply(null, args); 
};

The only difference is we're using the window or global dictionary to access the function.

EDIT: Added passing parameters.

You can do like this;

 function foo(v){console.log("foo: ",v)}; function bar(v){console.log("bar: ",v)}; var funs = ["foo", "bar"], i = 0; while (i < funs.length) this[funs[i]](i++); 

Well of course your functions definitions might reside in a particular scope and you may need to invoke them from within whatnot..! In that case you can of course wrap the above code in a function and bind it to whatever scope your function definitions are made in. Such as

 var obj = { foo: function(v){console.log("foo: ",v)}, bar: function(v){console.log("bar: ",v)} }, funs = ["foo", "bar"], runner = function(a){ var i = 0; while (i < a.length) this[a[i]](i++); }.bind(obj); runner(funs); 

  1. You can call a function by its name like this:

    const functions = ['index', 'push'...];

     functions[0]() // write your parameters inside. this will call 'index' 
  2. If those function are not async, just write the callings one after another. If they are async, use a helper like async.waterfall or async.series.

  3. see 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM