Javascript Node.js“readline”未按预期工作

Javascript Node.js“readline”未按预期工作,javascript,readline,Javascript,Readline,我试图获取用户输入,将其保存到变量中,并对其执行其他操作,但readline函数的工作方式与我预期的不同 这是我的密码: var readline = require('readline') var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var response rl.question("Enter a number ", function (answe

我试图获取用户输入,将其保存到变量中,并对其执行其他操作,但readline函数的工作方式与我预期的不同

这是我的密码:

var readline = require('readline')

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var response
rl.question("Enter a number ", function (answer) {
    response = answer
    rl.close();
});

console.log('The user entered: ', response)

回调中的代码仅在用户实际键入一行时运行。您的console.log不会等待这种情况发生。接口是异步的


将console.log调用移到回调中,您将看到它是有效的。

回调中的代码仅在用户实际键入一行时运行。您的console.log不会等待这种情况发生。接口是异步的

var readline = require('readline')

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var response
rl.question("Enter a number ", function (answer) {
    response = answer
    outside();
    rl.close();
});

outside = function(){
    console.log('The user entered: ', response)
}
将console.log调用移到回调中,您将看到它是有效的

var readline = require('readline')

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var response
rl.question("Enter a number ", function (answer) {
    response = answer
    outside();
    rl.close();
});

outside = function(){
    console.log('The user entered: ', response)
}
console.log在用户向标准输入中输入任何内容之前运行

异步nodej的本质有时很难理解。试试上面的代码就可以了

console.log在用户向标准输入中输入任何内容之前运行


异步nodej的本质有时很难理解。试试上面的代码就可以了。

hmmm,但是我以后如何在回调块之外的代码中使用响应变量呢?@UndoolSipper你不知道。构造代码,使您需要对文本行执行的工作可以作为函数调用,并从.question回调函数调用该函数。这是JavaScript.hmmm中异步编程的一般性质,但是我以后如何在回调块之外的代码中使用响应变量呢?@UndoolSipper您不知道。构造代码,使您需要对文本行执行的工作可以作为函数调用,并从.question回调函数调用该函数。这是JavaScript中异步编程的一般性质。它可以工作,但我不知道如何利用它。假设在回调rl.question之后,我想在for循环中使用response。它只会给我错误,除非我在回调函数中执行所有操作。有办法解决这个问题吗?你可以运行一个循环setIntervalCheckUserResponsed,800;刚刚看到你的编辑。这很有效。谢谢。它很管用,但我不知道如何利用它。假设在回调rl.question之后,我想在for循环中使用response。它只会给我错误,除非我在回调函数中执行所有操作。有办法解决这个问题吗?你可以运行一个循环setIntervalCheckUserResponsed,800;刚刚看到你的编辑。这很有效。谢谢