Search code examples
javascriptnode.jsreadline

readline.question doesn't run X times inside the loop


I am having some troubles with the readlinemodule in Node.js. I need to ask for the customer id as many times as previous question response, but it asks once for it.

This is my current code:

const readline = require('readline');
var prompts = {
    numEmails: null,
    customerIds: [],
    email: null,
    password: null
}

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

//Ask for new question
rl.question('Num Emails: ', (numEmails) => {
    for(let i = 0; i<numEmails; i++) {
        //Ask for new question
        rl.question('Id Customer' + i+1 + ': ', (customerId) => {
            prompts.customerIds.push(customerId)
        })
    }
});

When I run the script, after answering I want the loop to run 4 times, it should ask for Id Customer 4 times, but it only does it once:

enter image description here

What am I doing wrong?


Solution

  • That happens because question method works async, so you need to wait for every answer, before starting a new question. You can handle that in the following manner.

    //Ask for new question
    rl.question('Num Emails: ', async (numEmails) => {
        for (let i = 0; i<numEmails; i++) {
            // Wait for a question to be answered. 
            await new Promise((resolve) => {
              rl.question('ID Customer ' + i+1 + ': ', (customerId) => {
                prompts.customerIds.push(customerId)
                
                resolve()
              }) 
            })
        }
    });
    

    I am using async/await syntax to work with promises, you can read more about it on the Internet. The idea is that I wrapped the question call into a Promise then when I receive an answer I resolve the promise so we will ask next question.