Arkin Solomon
Arkin Solomon

Reputation: 606

Function with readline is run in for loop before getting a response (Node.Js)

when I want to make a program that makes prompts based on how many the user wants. I have the prompts and the input figured out, the issue is that when the for loop runs, it will ask the question multiple times and not wait for a response. My code:

function mainLoop(auth, num){
    var i;
    for (i = 1; i <= numOfPrompts; i++){
        ask(auth);
        //Create the prompts (unrealated)
    }
}

function ask(auth){
    const r3 = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    r3.question("Do you like pie [Y/N]? ", (ans) => {
        ansCheck(auth, ans);
    });
}

function ansCheck(auth, ans){
    if (ans == "y" || ans == "yes"){
        variable = true;
    }else if (ans == "n" || ans == "no"){
        variable = false;
    }else{
        console.log("Invalid answer\n");
        ask(auth);
    }
}

If the user inputs 5, the output would be:

Do you like pie [Y/N]? Do you like pie [Y/N]? Do you like pie [Y/N]? Do you like pie [Y/N]? Do you like pie [Y/N]? 

I need the output to be:

Do you like pie [Y/N]? 

Wait for the answer...
Answer inputted so check the answer...
Answer checked so do unrelated things...
Repeat while needed.

Thank you for any help you can provide.

Upvotes: 0

Views: 978

Answers (1)

Steven Spungin
Steven Spungin

Reputation: 29081

The readline is async, so you should not use a loop.

Call ask from ansCheck after a valid response, just like you do for an invalid answer, but increment the counter there and stop calling when counter >= numSongs.

Another solution is to promisify ask, and use async/await in the loop.

Upvotes: 1

Related Questions