简体   繁体   中英

multiple user prompts node.js

I am trying to query the user twice (more than once in general), but everything gets printed out together and the first response get processed by both functions. I believe this has to do with the asynchronous nature of node.js. Can you please point me towards module that would take care of this for me or an implementation in prompt module? Thank you.

 var prompt = require('prompt'); prompt.start(); console.log("Enter a number: "); prompt.get(['number'], function(err, result) { if (!isNaN(result.number)) { console.log("You entered a number."); } else { console.log("You did not enter a number."); } }); var prompt2 = require('prompt'); prompt2.start(); console.log("Enter a number again: "); prompt2.get(['number1', 'number2'], function(err, result) { if (Number(result.number1) > Number(result.number2)) console.log("The first input is bigger"); else if (Number(result.number1) == Number(result.number2)) console.log("Both inputs are equal"); else console.log("The second input is bigger"); }); 

I am not sure if you actually need both prompt instances. I think you can achieve what you want with only one prompt and just calling get second time within the first get 's callback.

 var prompt = require('prompt'); prompt.start(); console.log("Enter a number: "); prompt.get(['number'], function(err, result) { if (!isNaN(result.number)) { console.log("You entered a number."); } else { console.log("You did not enter a number."); } console.log("Enter a number again: "); prompt.get(['number'], function(err, result) { if (result.number < 20) console.log("small"); else if (result.number < 50) console.log("medium"); else console.log("large"); }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM