Promise内的Node.js readline [英] Node.js readline inside of promises

查看:89
本文介绍了Promise内的Node.js readline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用node.js包readline在命令行上获取用户输入,并且我想通过promise将输入的输入进行管道传输.但是,输入永远不会通过then链.我认为问题可能出在回调方法中实现了诺言这一事实​​,但我不知道该如何解决.

I'm trying to use the node.js package readline to get user input on the command line, and I want to pipe the entered input through promises. However, the input never gets through the then chain. I think the problem could come from the fact that the promises are fulfilled in the callback method, but I don't know how to solve that problem.

此问题的示例如下:

import rlp = require('readline');

const rl = rlp.createInterface({
    input: process.stdin,
    output: process.stdout
  });  

let prom = new Promise((fulfill, reject) => {
    rl.question('Enter input: ', input => rl.close() && fulfill(input));
});

prom.then(result => {console.log(result); return prom})
    .then(result => {console.log(result); return prom})
    .then(result => console.log(result));

如果在node.js中运行,该问题将出现一次,输入输入后,程序将停止.我希望它等到输入第一个输入后,再打印该输入并要求下一个输入.

If run in node.js, the question will appear once, after input has been entered the program just stops. I want it to wait until the first input has been entered, then it should print this input and ask for the next input.

提前谢谢!

推荐答案

一旦您的诺言得以兑现,就无需再等待了.我还将 rl.close()调用移到末尾,因为只需要调用一次即可.

Once your promise is resolved, there's no use of waiting for that again. I also moved the rl.close() call to the end, as it's needed to be called only once.

const rlp = require('readline');

const rl = rlp.createInterface({
        input: process.stdin,
        output: process.stdout

});

function ask() {
    return new Promise((resolve, reject) => {
        rl.question('Enter input: ', (input) => resolve(input) );
    });
}

ask()
.then((result) => { console.log(result); return ask(); })
.then((result) => { console.log(result); return ask(); })
.then(result => { console.log(result); rl.close() });

这篇关于Promise内的Node.js readline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆