简体   繁体   English

如何通过作为参数传递的名称调用函数?

[英]How to call a function by its name, passed as parameter?

How to call a function by its name, passed as parameter? 如何通过作为参数传递的名称调用函数? My use case is the next, I have a switch case where I set the data of an api ajax call, once that ajax is complete it should be call print function passing the data result as parameter. 接下来是我的用例,我有一个switch case ,其中设置了api ajax调用的data ,一旦完成了ajax,应该是调用print function ,将数据结果作为参数传递。 I'm not sure this is a good approach, is there any better and easier way to do what I'm trying? 我不确定这是否是一个好方法,是否有更好和更容易的方法来做我正在尝试的事情? Maybe with async / promises ? 也许与async / promises

function printUpcoming(data) {
    //stuff
}

function printRecently(data) {
    //stuff
}

function printPopular(data) {
    //stuff
}

function requestAjax(dataSend, callFunctionByName) {
    $.ajax({
        type: "POST",
        url: "api-url",
        headers: {
            "Accept": "application/json",
            "user-key": "userkey"
        },
        data: dataSend,
        dataType: 'json',
        success: function(data) {
            jsonVal = data[0];
            //Call the function print depending of switch case option
            callFunctionByName(jsonVal);
        }
    });
}

switch (param) {
    case "upcoming":
        dataSend = "fields * where whatever 1";
        functionName = printUpcoming();
        requestAjax(dataSend, functionName);
        break;
    case "recently":
        dataSend = "fields * where whatever 2";
        functionName = printRecently();
        requestAjax(dataSend, functionName);
        break;
    case "popular":
        dataSend = "fields * where whatever 3";
        functionName = printPopular();
        requestAjax(dataSend, functionName);
        break;
}

One option would be to group functions into an object: 一种选择是将功能分组为一个对象:

const Printer = {
    upcoming(data) {...},
    recently(data) {...},
    popular(data) {...},
}

and then 接着

requestAjax(dataSend, param)

and in requestAjax 并在requestAjax

Printer[funcName](jsonVal))

Another option, as @VLAZ suggested, is to get rid of callbacks completely: @VLAZ建议,另一种选择是完全摆脱回调:

async function requestAjax(dataSend) {...}

...

printUpcoming(await requestAjax(...))

Example: 例:

 function printUpcoming(x) { console.log('Upcoming!', x) } async function request() { return $.ajax('https://jsonplaceholder.typicode.com/todos/1') } async function process(param) { switch (param) { case "upcoming": printUpcoming(await request()); break; case "recently": printRecent(await request()); break; } } process('upcoming') 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

I recommend fetch over jQuery's $.get . 我建议通过jQuery的$.get fetch To call a function by it's name, you could use eval , but I do not recommend using eval! eval名称调用函数,可以使用eval但我不建议使用eval! It may lead to security risks and weird errors. 这可能会导致安全风险和奇怪的错误。 Instead, you can create index of your functions like this: 相反,您可以像下面这样创建函数的索引:

const AJAX_HANDLERS = { printUpcoming, printRecently, printPopular };

Then using fetch: 然后使用提取:

async function requestAjax(dataSend, handlerFunction) {

    if (typeof handlerFunction == "string") {
        // Convert "name" to "printName"
        const fnName = "print" + (handlerFunction).replace(/^([a-z])/i, (x, m1) => x.toLocaleUpperCase());
        if (typeof AJAX_HANDLERS[fnName] == "function") {
            handlerFunction = AJAX_HANDLERS[fnName];
        }
        else {
            throw new Error("Invalid function callback name: " + fnName)
        }
    }

    const fetchSettings = {
      method: 'POST',
      headers: {
        "Accept": "application/json",
        "user-key": "userkey"
      },
      body: dataSend
    };
    const result = await fetch("api-url", fetchSettings);
    const jsonResponse = await result.json();

    handlerFunction(jsonResponse[0]);
}

暂无
暂无

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

相关问题 如何知道函数的参数中传递的var名称? - How to know the var name passed in parameter for a function? 当其名称作为字符串传递给函数时,如何执行JavaScript函数? - How to execute a JavaScript function when its name is passed as a string in function? 如何将函数调用为另一个函数作为以字符串形式传递的参数 - How to call a function another function as a parameter passed as a string 如何调用在另一个函数中作为参数传递的函数 - how to call a function which is passed as parameter in another function 当在 jquery 中的 function 中将事件作为参数传递时,如何在“keydown”上调用 function - How to call a function on 'keydown' when an event is passed as a parameter in that function in jquery 如何使用 NPM 脚本中传递的参数调用 JS function - How to call a JS function with parameter passed in NPM script 如何根据传递给函数的参数更改变量名? - How can I change a variable name based on a parameter passed to a function? 如何使用JavaScript获取作为回调目的传递的函数名称作为参数 - How to get function name passed as parameter for callback purpose using Javascript Closure Conditional - 当它没有作为参数传递时,这个返回函数如何将值设置为参数? - Closure Conditional - How does this returning function get the value set as a parameter when its not passed as a parameter? 有没有办法调用作为参数传递的元素的函数? - Is there a way to call an element's function passed as parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM