javascript - Repeatedly prompt user until resolved using nodeJS async-await -


i try repeteadly asking question user until gave correct answer using code.

the problem is, won't resolve if user doesn't gave right answer @ first time.

var readline = require('readline'); var rl = readline.createinterface({     input: process.stdin,     output: process.stdout });  function promptage() {     return new promise(function(resolve){         rl.question('how old you? ', function(answer) {             age = parseint(answer);             if (age > 0) {                 resolve(age);             } else {                 promptage();             }         });     }); }  (async function start() {     var userage =  await promptage();     console.log('user age: ' + userage);     process.exit(); })(); 

here terminal outputs each condition:

when user gave right answer first time fine ...

how old you? 14 user age: 14 

when user gave wrong answer stuck (won't resolve , process won't exit) ...

how old you? asd how old you? 12 _ 

when user doesn't gave answer stuck ...

how old you?  how old you?  how old you? 12 _ 

could explain happened or give me reference article/video explain nature?

btw, try using async/await learning purpose (trying learn how things asynchronously). tried without async/await (promptage() doesn't return promise) , okay.

thank attention.

it's nothing parseint() although skellertor advising practice.

the problem you're generating new promise every time promptage() called - original caller i.e. start() has visibility of first promise. if enter bad input, promptage() generates new promise (inside never-resolved promise) , success code never run.

to fix this, generate 1 promise. there more elegant ways clarity, , avoid hacking code unrecognisable...

var readline = require('readline'); var rl = readline.createinterface({     input: process.stdin,     output: process.stdout });  // changes in promptage() // internal function executes asking, without generating new promise function promptage() {   return new promise(function(resolve, reject) {     var ask = function() {       rl.question('how old you? ', function(answer) {         age = parseint(answer);         if (age > 0) {           // internal ask() function still has access resolve() parent scope           resolve(age, reject);         } else {           // calling ask again won't create new promise - 1 ever created , resolves on success           ask();         }       });     };     ask();   }); }  (async function start() {     var userage =  await promptage();     console.log('user age: ' + userage);     process.exit(); })(); 

Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -