0

I am trying to set a local variable with user input using prompt. I am using javascript and running it with node in the command line. I have installed the prompt module and I am using it in the method. The problem that I have is that the execution of statements after prompt.get() do not wait until user input is entered. The rest of the method I am writing relies on the option variable. I would like to set option before executing anything after prompt.get(). Here is the code

function main_loop(){
  var prompt = require('prompt');
  console.log("OPTIONS");
  console.log("=========");
  console.log("1. Use a potion");
  console.log("2. Go to the next room");
  console.log("3. Exclaim ' Die you wizard!!!'");
  console.log("4. Exit game");
  var option;
  prompt.get(['option'], function(err, result){
    option = result.option;
    console.log("option is: " + option);
  });
  console.log(option);

}
main_loop();

Here is the output. I run it through node and enter 1.

Blockquote

OPTIONS
=========
1. Use a potion
2. Go to the next room
3. Exclaim ' Die you wizard!!!'
4. Exit game
prompt: option:  undefined
1
option is: 1
jlesse
  • 564
  • 5
  • 11
  • Possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – JJJ Oct 02 '15 at 15:48

2 Answers2

0

prompt.get() is an asynchronous function. This means, it executes the get function an when it's done it executes the anonymous callback function (which sets the option to result.option), and simultaniously it jumps to the next statement, which is console.log(option).

This means the console.log(option) get's executed before the anonymous callback function has the chance to set the option to result.option.

Ello
  • 907
  • 1
  • 15
  • 33
-1

You could declare a variable and store the user input in it. Then use an if-statement to check if the variable is empty or not. If it is not empty (the user typed something) you could start outputting the things in the order you like.

Hiltje
  • 140
  • 1
  • 5