Javascript 为什么我的箭头函数错误为“非函数”?
我试图使用readline包提示用户输入一系列信息。据我所知,我已将每个提示符作为回调传递,因此我将它们设置为箭头函数,就像在go函数中一样。程序流为getLowerBounds到getUpperBounds以关闭 发生的情况是,我得到第一次输入的提示,输入起始范围:[4000000]->。输入输入后,我得到错误类型error:nextFn不是函数 这是我的密码:Javascript 为什么我的箭头函数错误为“非函数”?,javascript,typescript,Javascript,Typescript,我试图使用readline包提示用户输入一系列信息。据我所知,我已将每个提示符作为回调传递,因此我将它们设置为箭头函数,就像在go函数中一样。程序流为getLowerBounds到getUpperBounds以关闭 发生的情况是,我得到第一次输入的提示,输入起始范围:[4000000]->。输入输入后,我得到错误类型error:nextFn不是函数 这是我的密码: import * as Readline from 'readline'; class InputPrompts { pr
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替换了arrow函数体,但仍然得到了相同的错误
您没有将getUpperBounds/getLowerBounds中的下一个参数传递给getInput调用
当不传递可选参数时,该值将是未定义的。您的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);
}
您没有将getUpperBounds/getLowerBounds中的下一个参数传递给getInput调用
当不传递可选参数时,该值将是未定义的。您的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);
}
那太尴尬了。第一个要点就是它。谢谢你发现我的错误,真尴尬。第一个要点就是它。谢谢你发现我的错误。