Reputation: 41
This is some homework I have. I want it to read user input and then create two objects, giving them values based on the user input. Here is my code, beginning at the top of the JS file:
console.log("Type 'help' for commands");
console.log("Square numbers:");
console.log("Enter player 1 name");
var player1 = new Player(readLine());
var player2 = new Player(readLine());
console.log("logging name after making players" + player1.name);
function readLine() {
var inputText;
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter player name? ", function(answer) {
inputText = answer;
console.log("Player name:", answer);
rl.pause();
});
return inputText;
}
Here is the output I get: http://oi60.tinypic.com/9tn7nn.jpg
I'm used to C# and Java and in those languages, readline() would wait for the input and then create the object with whatever I inputted, before moving onto the next line. Not in JS though! It just carries on, calling readline() twice before I've typed anything in (therefore printing "prompt>" twice) and then logging player 1's name (before typing it in, hence undefined). Then it waits for me to type something in and once I type something, it sets both players to the one name and then ends the program.
Is it possible to do what I am trying to get it to do? Is there another way I can get input to work without it skipping past it and running the rest of the code?
Thanks in advance!
Upvotes: 3
Views: 17670
Reputation: 161637
You have made several incorrect assumptions about JavaScript. The primary issue being that rl.question(...)
shows the prompt to the user, but it can do nothing to block the JS thread itself, so your readline()
function will immediately exit with undefined
because function(answer)
has not run yet because the user has not typed anything yet. A simple way to structure your code would be:
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.write("Type 'help' for commands\n");
rl.write("Square numbers:\n");
function createPayer(number, callback){
rl.question("Enter player " + number + " name? ", function(answer) {
var player = new Player(answer);
// Call the callback function once the player is created.
callback(player);
});
}
createPayer(1, function(player1){
createPayer(2, function(player2){
console.log("logging name after making players" + player1.name);
console.log("logging name after making players" + player2.name);
// Then call player logic you have from in here.
});
});
The key being that there is no explicit 'wait' anywhere in here. JS code is primarily event and callback based, so instead of waiting for the user to type something, you queue up a function to be called once they have entered something.
Upvotes: 8