Node.js readline inside of promises

♀尐吖头ヾ 提交于 2021-02-10 12:16:06

问题


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.

An example of this problem looks like this:

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

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.

Thanks in advance!


回答1:


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



回答2:


Here's an answer from this question here for which I deserve no credit.


// Function
function Ask(query) {
  const readline = require("readline").createInterface({
    input: process.stdin,
    output: process.stdout
  })

  return  new Promise(resolve => readline.question(query, ans => {
  readline.close();
  resolve(ans);
}))
}

 
// example useage
async function main() {

 var name = await Ask("whats you name")
 console.log(`nice to meet you ${name}`)

 var age = await Ask("How old are you?")
 console.log(`Wow what a fantastic age, imagine just being ${age}`)
}

main()



回答3:



const readline = require('readline');

const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const ask = (query) => new Promise((resolve) => rl.question(query, resolve));

ask('A: ').then(async (a) => {
  const b = await ask('B: ');
  const c = await ask('B: ');

  console.log(a, b, c);

  rl.close();
});

rl.on('close', () => process.exit(0));



来源:https://stackoverflow.com/questions/47998851/node-js-readline-inside-of-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!