gpt4 book ai didi

javascript - 等待在 while 循环中不工作

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:30 26 4
gpt4 key购买 nike

我的应用代码:

const readline = require('readline');

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
async function init() {
while (true) {
console.log("TICK");
await (rl.question('What do you think of Node.js? ', await (answer) => {

console.log('Thank you for your valuable feedback:', answer);



rl.close();
}))
await new Promise(resolve => setTimeout(resolve, 1000))
}
}

它必须如何工作(或者我认为它应该如何工作):

当我们遇到 await (rl.question('... 它应该等待响应(用户输入)并且只比循环继续。

实际运作方式

当它遇到 await new Promise(resolve => setTimeout(resolve, 1000)) 时它正在工作,但是 await (rl.question('... 你获取输出但代码继续执行而不等待用户输入。

最佳答案

async 函数需要一个返回 promise 的函数。 rl.question 不返回 promise ;它需要回调。所以你不能只是把 async 放在它前面,希望它能工作。

可以通过将其包装在一个 promise 中使其工作,但这可能比它值得的工作更多:

const readline = require('readline');

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

function rl_promise(q) {
return new Promise(resolve => {
rl.question('What do you think of Node.js? ', (answer) => {
resolve('Thank you for your valuable feedback:', answer)
})
})
}
async function init() {
while (true) {
console.log("TICK");
let answer = await rl_promise('What do you think of Node.js? ')
console.log(answer)
}
rl.close();
}

init()

话虽如此,更好的方法是避免 while 循环并设置停止条件。例如,当用户键入“退出”时。我认为这更简单也更容易理解:

const readline = require('readline');

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

function ask() {
rl.question('What do you think of Node.js? ', (answer) => {
console.log('Thank you for your valuable feedback:', answer);
if (answer != 'quit') ask()
else rl.close();
})
}

ask()

关于javascript - 等待在 while 循环中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38679599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com