简体   繁体   中英

Await not working in while loop

My app code:

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

How it must work (or how i think it should work):

When we meet await (rl.question('... it should wait for the response (user input) and only than loop continue.

How it actually works

When it meets await new Promise(resolve => setTimeout(resolve, 1000)) it's working, but with await (rl.question('... you get output but code continue executing without waiting for user input.

async functions require a function that returns a promise. rl.question doesn't return a promise; it takes a callback. So you can't just stick async in front of it an hope it will work.

You can make it work by wrapping it in a promise, but this is probably more work than it's worth:

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

Having said that, a better approach is to avoid the while loop and have a stopping condition. For example, when the user types 'quit'. I think this is simpler and much easier to understand:

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 loop is not async. It is needed to use an async function as iteratee. You can find more info here:

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

Personally I've used Promise.map of bluebird.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM