首页 > 解决方案 > 为什么我的箭头函数错误为“不是函数”?

问题描述

我正在尝试使用 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(),我仍然得到同样的错误。

标签: javascripttypescript

解决方案


  • 您没有将next参数传递给getUpperBounds/调用getLowerBoundsgetInput
  • 当不传递可选参数时,该值将为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);
}

推荐阅读