我正在尝试使用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();
我不确定是什么问题。我看了这个article。我用console.log()
替换了箭头函数体,但仍然遇到相同的错误。
答案 0 :(得分:3)
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);
}