如何同步使用readline?

How can I use readline synchronously?

我只是想等待用户输入密码,然后在继续我的其余代码之前使用它。错误是 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 的 question() 函数不 return 箭头函数的 Promise 或结果。因此,您不能将 then() 与它一起使用。你可以简单地做

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

如果你真的需要用 Promise 构建一个链,你可以用不同的方式编写你的代码:

new Promise((resolve) => {
    rl.question('Password: ', (password) => {
        rl.close();
        resolve(password);
    });
}).then((password) => {
   return decrypt(password); //returns Promise
}).then((data) => {
   console.log(data); 
});

您可能不应该忘记 .catch(),否则任何一种解决方案都有效,选择应基于哪个代码更易于阅读。

您可能还想再看几个 promise usage patterns

如果您害怕使用回调和回调地狱的可能性。您可以查看 readline-sync package