我正在尝试对具有参数的函数进行引用ep
。因此,我制作了以下PoC,以说明我遇到的问题。
selectFunction()
中的3个函数都采用不同的参数,并且在现实世界中包含axios
函数,所以这就是我有await
的原因。
在下面的表格中,我得到了TypeError: ep is not a function
。
问题
有人能找出问题出在哪里吗?
(async () => {
function getStatusCode(p) {console.log("hi")};
function getString(p) {console.log("hi")};
function getSecureString(p) {console.log("hi")};
const p = {"type": 1, "string": 2, "host": 3};
function selectFunction(p) {
switch (p.type) {
case 1:
return getStatusCode({
url: p.url
});
break
case 2:
return getString({
string: p.string
});
break
case 3:
return getSecureString({
hostname: p.host
});
break
default:
throw "error";
};
};
// ep should be a function reference
const ep = selectFunction(p);
console.log(typeof ep);
const isOk = await ep();
})();
您返回的是调用函数的结果,而不是函数本身。
如果您需要这样做,您可能会发现通过将selectFunction
中的调用包装为匿名函数来显式返回函数引用是成功的:
function selectFunction(p) {
switch (p.type) {
case 1:
return function(arg) {
return getStatusCode({
url: arg.url
})
};
case 2:
return function(arg) {
return getString({
string: arg.string
})
};
case 3:
return function(arg) {
return getSecureString({
hostname: arg.host
})
};
default:
throw "error";
};
};
const ep = selectFunction(p)
将ep
设置为selectFunction
返回的值,并将p
作为参数。
如果您希望以后使用ep(p)
并期望它像selectFunction(p)
一样工作,这应该是可行的:
const ep = p => selectFunction(p);
它是一个箭头函数。
它不执行selectFunction
,而是引用它
以下代码的优点是selectFunction()
只运行一次。
const delay = require('delay');
(async () => {
function getStatusCode(p) {console.log("hi1")};
function getString(p) {console.log("hi2")};
function getSecureString(p) {console.log("hi3")};
const p = {"type": 3, "string": 2, "host": 3};
function selectFunction(p) {
console.log("only run once");
switch (p.type) {
case 1:
return getStatusCode;
break
case 2:
return getString;
break
case 3:
return getSecureString;
break
default:
throw "error";
};
};
// ep should be a function reference
const ep = selectFunction(p);
console.log(typeof ep);
while (true) {
const isOk = await ep();
await delay(1000);
};
})();