Repeatedly request a user for permission using nodeJS async-wait

I am trying to re-ask the user a question until they give the correct answer using this code.

The problem is that it will not be resolved if the user did not give the correct answer for the 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 are 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 are the terminal outputs for each condition:

When the user gave the correct answer for the first time, that was good ...

How old are you? 14
USER AGE: 14

When the user gave the wrong answer, he was stuck (will not be allowed and the process will not exit) ...

How old are you? asd
How old are you? 12
_

When the user did not give any answer, he was also stuck ...

How old are you? 
How old are you? 
How old are you? 12
_

Can someone explain what happened or give me a link to an article / video explaining this character?

Btw, , async/await ( ). async/await (promptAge() ), .

.

+4
2

parseInt(), skellertor .

, , promptAge(), , .. start(), . , promptAge() ( ), .

, Promise. , - ...

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

// the only changes are in promptAge()
// an internal function executes the asking, without generating a new Promise
function promptAge() {
  return new Promise(function(resolve, reject) {
    var ask = function() {
      rl.question('How old are you? ', function(answer) {
        age = parseInt(answer);
        if (age > 0) {
          // internal ask() function still has access to resolve() from parent scope
          resolve(age, reject);
        } else {
          // calling ask again won't create a new Promise - only one is ever created and only resolves on success
          ask();
        }
      });
    };
    ask();
  });
}

(async function start() {
    var userAge =  await promptAge();
    console.log('USER AGE: ' + userAge);
    process.exit();
})();
+2

, parseInt(). , . , int.

+1

Source: https://habr.com/ru/post/1683981/


All Articles