0

I am trying to create a loop where I can keep prompting myself question while not exiting the loop until I enter 1. however it is not working at the moment, any advise?

var prompt = require('prompt');             //require to use prompt
var sync = require('sync');                //require to use synchronous function

var choice = 0;

sync(function()
{
while(choice != 1)
{
    if(choice == 0)
    {

        prompt.start();

        prompt.get(['message'], function(err, result)
        {
            if (err)
            {
                return onErr(err);
            }
            data(result.message);
            choice = result.message;
        });

    }
    else if (choice == 1)
    {
        break;
    }
}
});
4
  • The callback you pass to prompt.get() never has a chance to run because the while is blocking the job queue. Learn about run to completion: developer.mozilla.org/en-US/docs/Web/JavaScript/… . Commented Mar 17, 2016 at 4:33
  • I suggest you use the debugging technique of executing this in your head. Commented Mar 17, 2016 at 4:33
  • 1
    Assuming you are just starting with node, you should learn how to use callbacks (and make a recursive solution instead of the while loop). Commented Mar 17, 2016 at 4:34
  • If you're really determined to use sync, you should check again its docs. You'd need to call var result = prompt.get.sync(['message']). Commented Mar 17, 2016 at 4:35

1 Answer 1

1

Classic loops don't play well with async code. You need another approach:

var prompt = require('prompt');

prompt.start();

function read() {
    prompt.get(['message'], function(err, result) {
        if (err) {
            return onErr(err);
        }
        console.log(result.message);
        if (result.message != 1) {
            read();
        }
    });
}

read(); 
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.