How can I use readline synchronously?

I am just trying to wait for a user to enter a password, and then use it before navigating through the rest of my code. Error 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); }); } 
+6
source share
2 answers

The Readline question() function does not return a Promise or the result of an arrow function. So you cannot use then() with it. You can just do

 rl.question('Password: ', (password) => { rl.close(); decrypt(password).then(data => { console.log(data); }); }); 

If you really need to 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 should probably not forget about .catch() , otherwise any solution will work, the choice should be based on which code will be easier to read.

You can see a couple of additional promise usage patterns

+1
source

And if you are afraid to use callbacks and the ability to call back hell. You can check readline-sync file

0
source

Source: https://habr.com/ru/post/1014753/


All Articles