0

I'm trying to get an input from the keyboard by calling a function that uses the built-in readline module, but it seems that the loop "doesn't wait" for each function call to finish.

The main function is supposed to print the 4 different numbers that are inputted.

I've tried using async-await on my main function, but that had the same result. Is async-await even needed for this?

I'm using the command node input.js in terminal to run the program. No HTML.

function getInput(question) {
  var readline = require('readline');

  var rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
  });
  rl.question(question, function (x) {
    var aString = parseInt(x);
    rl.close();
    entered = true;
    return aString;
  });

}

async function main() {
  var i = 0;
  var myGuess;
  while (i <= 3) {
    myGuess = await getInput("Enter something: ");
    console.log(myGuess);
    i++;
  }
}
main();

I expect to see:

Enter something: 3 // just entering random numbers
3
Enter something: 9
9
Enter something: 12
12
Enter something: 55
55

But I get:

Enter something: undefined
Enter something: undefined
Enter something: undefined
Enter something: undefined
2222                         // I only got to enter 2...



1 Answer 1

1

read how to use await

The await operator is used to wait for a Promise. It can only be used inside an async function.

  return new Promise((resolve, reject) => {
    rl.question(question, function (x) {
      var aString = parseInt(x);
      rl.close();
      entered = true;
      return resolve(aString);
    });
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.