简体   繁体   English

Node.js Readline暂停代码

[英]Node.js Readline Pause Code

Sorry I've just dipped my feet in JavaScript, and currently trying to collect user input from the console. 抱歉,我刚刚开始使用JavaScript,目前正在尝试从控制台收集用户输入。 I have a code that looks like this: 我有一个看起来像这样的代码:

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();

So if I try to run this, it'll show: 因此,如果我尝试运行此命令,它将显示:

Lemme test: undefined

and then wait for me to input. 然后等我输入。 Apparently console.log(num); 显然console.log(num); ran before getInput(); getInput();之前运行getInput(); was finished, or getInput(); 完成,或getInput(); spits out an undefined then ask for input. 吐出一个undefined然后要求输入。

BTW switching rl.close(); BTW切换rl.close(); and return ans; return ans; does not work. 不起作用。

Why does this happen? 为什么会这样?

This happened because node doesn't wait for readline to get input - like almost everything in Node, it is asynchronous. 发生这种情况是因为Node不等待readline获得输入-就像Node中的几乎所有内容一样,它是异步的。 So it fires off the request for user input and continues on with the program. 因此,它会触发用户输入请求,并继续执行该程序。 Once there is some user input, if fires the callback you gave it. 一旦有用户输入,如果触发您提供的回调。 So to deal with this you need to manage the use input in the callback or have a function that is called in the callback to deal with the input asynchronously. 因此,要解决此问题,您需要管理回调中的use输入或具有在回调中调用的函数以异步处理输入。 For example: 例如:

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();

That's because the getInput function is a callback which means that it's executed at some point in the future so the console.log , which is not a callback, gets executed before. 这是因为getInput函数是一个回调,这意味着它将在将来的某个时刻执行,因此不是回调的console.log会在之前执行。

A function or a method it's a callback when you assign it to another function like this: 当您将一个函数或方法分配给另一个函数时,它就是一个回调:

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
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM