I'm simply trying to wait for a user to enter a password and then use it before moving on the rest of my code. The error is Cannot read property 'then' of undefined
.
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Password: ', password => {
rl.close();
return decrypt(password);
}).then(data =>{
console.log(data);
});
function decrypt( password ) {
return new Promise((resolve) => {
//do stuff
resolve(data);
});
}
I'm simply trying to wait for a user to enter a password and then use it before moving on the rest of my code. The error is Cannot read property 'then' of undefined
.
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Password: ', password => {
rl.close();
return decrypt(password);
}).then(data =>{
console.log(data);
});
function decrypt( password ) {
return new Promise((resolve) => {
//do stuff
resolve(data);
});
}
Share
Improve this question
edited Feb 7, 2017 at 2:48
yeputons
9,2481 gold badge36 silver badges71 bronze badges
asked Feb 7, 2017 at 2:12
Dustin RaimondiDustin Raimondi
4231 gold badge5 silver badges10 bronze badges
1
-
1
It looks like
rl.question
does not return promise in vanilla Node.Js (I'm assuming the question is about node.js). Actually, it returns nothing, see source code. So I'd expect that there is nothen
method on it. So if you really need a promise, I think you'll have to implement it manually. – yeputons Commented Feb 7, 2017 at 2:27
2 Answers
Reset to default 4Readline's question()
function does not return Promise or result of the arrow function. So, you cannot use then()
with it. You could simply do
rl.question('Password: ', (password) => {
rl.close();
decrypt(password).then(data => {
console.log(data);
});
});
If you really need to build a chain with Promise, you can pose your code differently:
new Promise((resolve) => {
rl.question('Password: ', (password) => {
rl.close();
resolve(password);
});
}).then((password) => {
return decrypt(password); //returns Promise
}).then((data) => {
console.log(data);
});
You probably should not forget about the .catch()
, otherwise either solution works, the choice should be based on which code will be easier to read.
You may want to look at a couple of additional promise usage patterns
And if you are scared of using callbacks and the possibility of callback hell. You can check readline-sync package