0

I am new to javascript and I do not know how to wait on each iteration to take input and print or process. I am working in node application.

for(let i=0;i<3;i++){
  const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
  });
  readline.question('what should be tha name?', inputName => {
    console.log(`Hi ${inputName}`)
    readline.close();
  });
}

If I am putting ray as input for above it prints Hi ray for 3 times. I need it to take input for each time.

UPDATE:

I have made following changes but still it is working as per my need, when I press any letter it took it for all 3 iteration. i want 3 different input which will be taken synchronously.

const readline = require('readline');

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

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

const arr = [1,2,3]
arr.forEach(async element => {
    const ans = await askQuestion("Are you sure you want to deploy to PRODUCTION? ");
    console.log({ans})
});
ray
  • 5,454
  • 1
  • 18
  • 40

1 Answers1

1

Try readline-sync:

const readline = require('readline-sync');

const arr = [1,2,3]
arr.forEach(() => {
    const ans = readline.question("Are you sure you want to deploy to PRODUCTION? ");
    console.log({ans})
});
Christian
  • 7,433
  • 4
  • 36
  • 61