[英]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.