Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use readline synchronously?

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);
    });
}
like image 944
Dustin Raimondi Avatar asked Feb 07 '17 02:02

Dustin Raimondi


1 Answers

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

like image 121
Alex Pakka Avatar answered Sep 30 '22 04:09

Alex Pakka