Dustin Raimondi
Dustin Raimondi

Reputation: 423

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);
    });
}

Upvotes: 9

Views: 6502

Answers (2)

Alex Pakka
Alex Pakka

Reputation: 9706

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

Upvotes: 4

Femi Oladeji
Femi Oladeji

Reputation: 365

And if you are scared of using callbacks and the possibility of callback hell. You can check readline-sync package

Upvotes: 2

Related Questions