为什么我的箭头函数错误地显示为“不是函数”?

时间:2020-01-09 21:29:36

标签: javascript typescript

我正在尝试使用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()替换了箭头函数体,但仍然遇到相同的错误。

1 个答案:

答案 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);
}