0

I'm trying to read in a word from the console to use in a hangman-like application. So far the prompt of "enter your word" is showing up, but the application won't wait for input to continue.

I've set VS code to use an external console, tried using different methods without readline, and watched a few videos to try and get this to work.

var readline = require('readline');

var rl = readline.createInterface(process.stdin, process.stdout);

function getWord(){

    var word = "";

    rl.question("Enter your word", function(answer){
        word = answer
    })

    var wordArray = word.split('');

    return wordArray;
}

console.log(getWord());

I would expect it to wait for input then continue but it doesn't.

Mark
  • 90,562
  • 7
  • 108
  • 148
Ryan Callahan
  • 115
  • 1
  • 11
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jordan Running May 23 '19 at 21:48

1 Answers1

2

rl.question performs an async operation, so you cannot be sure that word is equals to answer when you try to .split. However, you are sure that user has typed something into the callback that receives answer as parameter.

In other words, you have to change your code to handle this situation, you might consider the usage of a Promise:

var readline = require('readline');

var rl = readline.createInterface(process.stdin, process.stdout);

const getWord = () => {
  return new Promise(resolve => {
    rl.question("Enter your word", function(answer) {
        resolve(answer.split(''));
    });
  });
}

getWord().then(array => {
  console.log(array);
  process.exit(0);
});
Matteo Basso
  • 2,694
  • 2
  • 14
  • 21