2

I'm new in node.js. I know it uses asynchronous programming but I need to write a loop for asking user to input some data and then after user inputs data, ask again and again till the loop ends. I tried this code but the output is like this:
Insert Data?
Insert Data?
Insert Data?
and when I wanna input something it's like: aaallliii

for (index=1;index<=3;index++){
    console.log("Insert Data?");
    prompt.start();
    prompt.get(['data'], function (err, result) 
    {
    });
    }

how can I write the code to use it like normal loops?

5
  • I know it uses asynchronous programming only the asynchronous parts are asynchronous, the synchronous parts are ... drum roll ... syncrhonous ... what is prompt in your code? Commented Oct 14, 2017 at 6:19
  • @JaromandaX I run code in command line, prompt helps me to ask user for data i think. I found it in stackoverflow. Commented Oct 14, 2017 at 6:21
  • 1
    Look into using async/await for the easiest solution, otherwise look into Promises and resolving them in series. Commented Oct 14, 2017 at 6:22
  • but none of this code needs anything asynchronous - so if prompt is in some way asynchronous, then it's the wrong tool - a link to what prompt is would help Commented Oct 14, 2017 at 6:23
  • If you're using node... chances are you're going to need something asynchronous Commented Oct 14, 2017 at 6:33

1 Answer 1

5

Here's a solution that uses async/await, if you are able to use node v7.6.

async/await lets you use asynchronous stuff and write the code in a way that looks more synchronous. In your case, you want to prompt the user for input, then await their response before continuing. The await keyword lets you write the code in the same way, "blocking" until the user has given input (although everything is still asynchronous, it's just syntactic sugar basically)

async function insertData() {
    for (let index = 1; index <= 3; index++) {
        console.log("Insert Data?");
        prompt.start();
        let input = await new Promise(resolve => {
            prompt.get(['data'], (err, result) => {
                resolve(result);
            }
        });
        // do something with input
    }
}

insertData().then(() => console.log("Done prompting."));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This was exactly what i wanted.

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.