0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.