我正在尝试使用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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句