I find it very hard to explain or search for this problem, so I'm asking Stack Overflow.
I'm asking user for user-input in the terminal several times and want to make a function out of it. A function that takes a question and a variable, and the input should be added to the variable.
This is my code:
var name = 'hello',
age = '11'
var readline = require('readline');
// var rl = readline.createInterface(process.stdin, process.stdout);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var getInput = function(inputVariable, question, cb) {
rl.question(question, function(answer) {
inputVariable = answer;
rl.close();
cb();
});
}
var askForName = function() {
console.log(1,age, name);
getInput(name, "What's your name? ", askForAge);
}
var askForAge = function() {
console.log(2,age, name);
getInput(age, "How old are you? ", printIt);
}
var printIt = function() {
console.log("Hello, " + name);
console.log(".. and " + age + " old.");
}
askForName();
Thanks!
In node.js applications, this is usually solved using either a callback chain or promises.
Using callbacks, you could write your code like this:
var getInput = function(question, cb) {
rl.question(question, function(answer) {
// Don't set the variable, but return value to callback
rl.close();
cb(answer);
});
}
// ask* take a callback which they call with the value
var askForName = function(cb) {
getInput("What's your name? ", cb);
}
var askForAge = function(cb) {
getInput("How old are you? ", cb);
}
// printIt takes the values as parameters
var printIt = function(name, age) {
console.log("Hello, " + name);
console.log(".. and " + age + " old.");
}
// Now ask for name and age and store them as local variables
// inside callbacks
askForName(function(name) {
askForAge(function(age) {
printIt(name, age);
});
});
I added comments to explain the changes. Basically, the values are only being passed between callbacks, never exposed to another scope.
When you pass a variable to a function, changing the reference to it will not affect the original variable. You can modify the variable's properties. However, that shouldn't be used as the main method of passing around variables.
A common way of passing a response from an asynchronous process is to use a callback function. You've almost got it:
var getInput = function( question, cb ) {
rl.question(question, function(answer) {
rl.close();
cb(answer);
});
}
var askForName = function( cb ) {
getInput("What's your name? ", cb);
}
var askForAge = function( cb ) {
getInput("How old are you? ", cb);
}
var printIt = function( name, age ) {
console.log("Hello, " + name);
console.log(".. and " + age + " old.");
}
askForName(function(name) {
askForAge(function(age) {
printIt( name, age );
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With