等待不在while循环中工作

时间:2016-07-31 00:01:31

标签: 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 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('...会得到输出但代码会继续执行而不等待用户输入。

2 个答案:

答案 0 :(得分:1)

async函数需要一个返回promise的函数。 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()

答案 1 :(得分:0)

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

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

我个人使用了蓝鸟的Promise.map。