如何同步使用readline? [英] 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);
});
}
推荐答案
Readline的 question()
函数不返回Promise或箭头函数的结果。所以,你不能使用 then()
。你可以简单地做
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);
});
});
如果你真的需要用Promise构建一个链,你可以用不同的方式编写代码:
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);
});
你可能不应该忘记 .catch()
,否则两种解决方案都有效,选择应该基于哪些代码更易于阅读。
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
这篇关于如何同步使用readline?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!