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);
});
}
Readline'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 compose 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
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