【问题标题】:Await not working in while loop等待不在while循环中工作
【发布时间】:2016-12-05 09:32:43
【问题描述】:

我的应用代码:

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('...,您会得到输出,但代码会继续执行而无需等待用户输入。

【问题讨论】:

  • 需要while循环吗?
  • @guest271314 ,是的。我想了解为什么有些异步工作而有些不工作。就像我的情况一样

标签: javascript node.js asynchronous async-await


【解决方案1】:

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 循环并设置停止条件。例如,当用户键入“退出”时。我认为这更简单,更容易理解:

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

【讨论】:

    【解决方案2】:

    虽然循环不是异步的。需要使用 async 函数作为 iteratee。你可以在这里找到更多信息:

    https://medium.com/@antonioval/making-array-iteration-easy-when-using-async-await-6315c3225838

    我个人使用的是 Bluebird 的 Promise.map。

    【讨论】:

    • 您的链接已损坏。也许我误解了,但你可以使用while 循环与async 函数。 OP 遇到的问题是他的函数没有返回承诺。
    • 链接已编辑,现在可以使用了。它帮助我处理不等待异步调用的 while 循环。
    猜你喜欢
    • 2015-07-18
    • 2012-05-20
    • 1970-01-01
    • 2013-05-19
    • 2010-12-26
    • 1970-01-01
    • 2021-08-14
    • 2012-10-13
    • 1970-01-01
    相关资源
    最近更新 更多