最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I use readline synchronously? - Stack Overflow

programmeradmin0浏览0评论

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 no then 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
Add a ment  | 

2 Answers 2

Reset to default 4

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 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

发布评论

评论列表(0)

  1. 暂无评论