繁体   English   中英

如何依次执行节点js函数,这些函数使用它们的名称在字符串数组中动态列出

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

我需要在Node.js程序中实现以下目标。

  1. 如何从字符串中提供的名称创建函数数组?
  2. 如何一个接一个地执行这些功能。 不是异步的。
  3. 如何为那些函数传递参数。

向我建议一种更好的方法来实现此目标或已经实现此目标的代码段。

步骤1.定义列表

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

步骤2.遍历列表

我们遍历函数列表并调用__call函数。

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

步骤3.调用函数

此步骤取决于框架。 如果使用节点,则必须使用global对象。 如果使用浏览器(HTML),则必须使用window对象。

对于前者,请使用:

__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); 
};

对于后者,请使用:

 __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); 
};

唯一的区别是我们使用windowglobal字典来访问该函数。

编辑:添加了传递参数。

你可以这样

 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++); 

当然,您的函数定义可能驻留在特定范围内,并且您可能需要从what ..!内部调用它们。 在那种情况下,您当然可以将上面的代码包装在一个函数中,并将其绑定到您定义函数的范围内。

 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. 您可以通过函数名称来调用它,如下所示:

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

     functions[0]() // write your parameters inside. this will call 'index' 
  2. 如果这些函数不是异步的,则只需一个接一个地编写调用。 如果它们是异步的,请使用async.waterfall或async.series之类的帮助器。

  3. 见1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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