Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 420
Src Avatar asked Jul 02 '26 18:07

Src


1 Answers

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()
like image 133
Mark Avatar answered Jul 04 '26 07:07

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!