node.jscallbackpromisereadline

Node.js readline inside of promises


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(resolve => {
  rl.question('Enter input: ', input => rl.close() && resolve(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!


Solution

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