Node.js Readline 暂停代码

Node.js Readline Pause Code

抱歉,我刚刚试了一下 JavaScript,目前正在尝试从控制台收集用户输入。我的代码如下所示:

main = () => {
    var num = getInput();
    console.log(num);
}

getInput = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.question('Lemme test: ', (ans) => {
        rl.close();
        return ans;
    });
}

main();

所以如果我尝试 运行 这个,它会显示:

Lemme test: undefined

然后等我输入。显然 console.log(num); 运行 在 getInput(); 完成之前,或者 getInput(); 吐出一个 undefined 然后要求输入。

顺便说一句,切换 rl.close();return ans; 不起作用。

为什么会这样?

发生这种情况是因为 node 不等待 readline 获取输入 - 就像 Node 中的几乎所有内容一样,它是异步的。因此它会触发用户输入请求并继续执行该程序。一旦有一些用户输入,如果触发你给它的回调。因此,要处理此问题,您需要在回调中管理使用输入,或者在回调中调用一个函数来异步处理输入。例如:

main = () => {
    var num = getInput();
}

dealWithInput = (str) => {
    console.log(str)
}

getInput = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.question('Lemme test: ', (ans) => {
        rl.close();
        dealWithInput(ans);
    });
}

main();

那是因为 getInput 函数是一个回调函数,这意味着它会在未来的某个时间点执行,所以 console.log 不是回调函数,它会在之前执行。

一个函数或方法,当你将它分配给另一个函数时,它是一个回调:

let example = () => {
   // This is a callback
}

doSomething(result => {
   // This is a callback too because its the same as doing the following
})

doSomething(function(result){
   // This is a callback without arrow functions
})