Javascript 等待在while循环中不工作
我的应用程序代码:Javascript 等待在while循环中不工作,javascript,node.js,asynchronous,async-await,Javascript,Node.js,Asynchronous,Async Await,我的应用程序代码: 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 Nod
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)(“…
时,它应该等待响应(用户输入),并且只有循环继续
它实际上是如何工作的
当它满足Wait new Promise(resolve=>setTimeout(resolve,1000))时,它正在工作,但是使用
Wait(rl.question(“…”
可以获得输出,但代码继续执行,而不等待用户输入。而循环不是异步的。需要使用异步函数作为迭代对象。您可以在此处找到更多信息:
就我个人而言,我使用过蓝鸟的Promise.map。
async
函数需要一个返回承诺的函数。rl.question
不返回承诺;它需要回调。因此,你不能将async
放在它前面,希望它能工作
你可以用承诺来实现它,但这可能比它的价值更大:
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循环并设置停止条件。例如,当用户键入“quit”时。我认为这更简单,也更容易理解:
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()
while
循环是否必要?@guest271314,是的。我想了解为什么有些异步工作,有些不工作。比如在我的例子中,你的链接断了。也许我误解了,但是你可以使用while
循环来处理async
函数。OP的问题是他的函数没有返回承诺。link edited、 现在它可以工作了。它帮助我避免了while循环等待异步调用。