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

just_a_programmer

我正在尝试使用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/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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

箭头函数错误:对象不是函数

为什么我会收到“ .then not function error”(。then不是函数错误)?

为什么我得到existsSync 不是函数错误?节点.js

Sequelize 字符串不是函数错误,为什么?

为什么我的函数错误地返回了2D数组的一部分?

我的Firebase Cloud Function失败,并显示Object.value不是函数错误?

为什么会收到“被调用对象0不是函数错误”的信息?

为什么Chrome抛出'getAttribute'不是for循环内的函数错误?

为什么会出现TypeError:L.Control.Draw不是构造函数错误?

订阅不是函数错误

调度不是函数错误

forEach不是函数错误

“调度”不是函数错误

.filter 不是函数错误?

.find不是函数错误

.autocomplete不是函数错误

getFeaturesByAttribute 不是函数错误

Java脚本箭头函数参数错误

为什么我导出的函数不是函数?

为什么我的过程的参数出现“不是函数”错误?

为什么我收到 onVideoSelect 不是函数的错误消息?

为什么我收到错误“button.addEventListener 不是函数”

为什么我在这里出现错误“不是函数”?

在我的情况下,AngularJS undefined不是函数错误

addEventListener 不是函数错误,当我使用 .split 时

是什么导致React不是函数错误?

为什么我会收到此 Cloud Firestore 函数错误?

为什么我会收到“没有匹配的构造函数错误?

为什么我使用简单的哈希函数出现非法参数错误?