javascript - 为什么我的箭头函数错误为“不是函数”?
问题描述
我正在尝试使用 readline 包来提示用户进行一系列输入。我的理解是,我已将每个提示作为回调传递,因此我将它们设为箭头函数,就像函数中所做的那样go()
。程序流程是 getLowerBounds() 到 getUpperBounds() 到 close()。
发生的情况是我收到第一个输入的提示Enter starting range: [4000000] ->
。输入我的输入后,我收到错误消息TypeError: nextFn is not a function
。
这是我的代码:
import * as Readline from 'readline';
class InputPrompts {
private readline: any;
constructor() {
this.readline = Readline.createInterface({
input: process.stdin,
output: process.stdout,
});
}
private getInput(message: string, def: any, nextFn?: any) {
this.readline.question(`${message}: [${def}] -> `, (answer) => {
if (nextFn === null) return;
nextFn(answer);
});
}
public getLowerBounds(next?: any) {
this.getInput('Enter starting range', 4000000);
}
public getUpperBounds(next?: any) {
this.getInput('Enter top of the range', 8999999);
}
public go() {
const endFn = (answer) => {
this.readline.close();
};
const upperFn = (answer) => {
console.log(`upperFn() got ${answer}`);
this.getUpperBounds(endFn);
};
this.getLowerBounds(upperFn);
}
}
function run() {
new InputPrompts().go();
}
run();
我不确定出了什么问题。我看过这篇文章。我用箭头函数体替换了console.log()
,我仍然得到同样的错误。
解决方案
- 您没有将
next
参数传递给getUpperBounds
/调用getLowerBounds
getInput
- 当不传递可选参数时,该值将为
undefined
. 您的getInput
方法仅针对null
.
我建议做
private getInput(message: string, def: any, next: (answer: string) -> void = () => {}) {
this.readline.question(`${message}: [${def}] -> `, next);
}
public getLowerBounds(next?: (answer: string) -> void) {
this.getInput('Enter starting range', 4000000, next);
}
public getUpperBounds(next?: (answer: string) -> void) {
this.getInput('Enter top of the range', 8999999, next);
}
推荐阅读
- reactjs - Google Maps React,使用 lat lng 添加标记
- php - Javascript window.open() 但在 Laravel
- asp.net - 奇怪的异常测试 EmailSender
- java - 如何从 spring maven 项目创建可执行文件?
- windows - Windows 10 正在丢失我选择的蜂窝 APN
- java - 在 SNMP 陷阱标头中发送 OID
- excel - 将列表视图控件添加到用户窗体时出现错误 800a9cf1
- angular - angualr6:iframe src 属性更新,但 pdf 有时不显示
- javascript - 根据字段,Typescript 将对象映射到包含新对象的数组
- action - google Assistant 和 Dialogflow 教程