-2

I have a function checkAge(age) which takes the user's age. The function checks whether the set age parameter is set correctly, if it is set incorrectly, the corresponding error should be generated and displayed in the console. I have some checks:

  • if the age value has not been set, you need to create the following error: "Please, enter your age",

  • If you set a negative age value, you need to create the following error: "Please, enter positive number",

  • if a non-numeric value of age was specified, you need to create the following error: "Please, enter number"

I need to output each error to the console and after each check, regardless of the results, output to the console "Age verification complete". Now I have a promise that displays an inscription in the console, regardless of the result, and also displays "Access allowed" in case of a good result. How can I create a chain with conditions?

function checkAdult(age) {
  return new Promise(function(resolve, reject) {
    if (typeof age === undefined) {
      resolve(console.log("Access allowed"));
    } else {
      reject(console.log("Error Please, enter your age"));
    }

    console.log("Age verification complete");
  });
}

checkAdult();

//checkAdult() Result: Error Please, enter your age
//                     Age verification complete

//checkAdult(-22) Result: Error Please, enter positive number
//                        Age verification complete
Jim G.
  • 15,141
  • 22
  • 103
  • 166
intern
  • 25
  • 5
  • 2
    can you give some example of what you've tried so far and why it didn't work? – RenokK Nov 08 '22 at 15:40
  • Sorry but it is unclear to me what it is what you are having trouble with, what you are describing should be easily solved with a simple if-else statements, also what is up with using Promise object? You don't have any asynchronous code in the example. – ncpa0cpl Nov 08 '22 at 15:42
  • if-else statements must be inside a Promise? Or is it correct to do it through then-catch? It's just a task to solve with Promise – intern Nov 08 '22 at 15:44
  • you can do the if statement inside the promise, if you want to resolve / reject the promise. but still, what have you tried so far and why didn't it work? – RenokK Nov 08 '22 at 15:46
  • I added as an example what I tried. And I have an error in the console. – intern Nov 08 '22 at 15:53

1 Answers1

1

You can do something like this:

function checkAdult(age) {
    return new Promise(function (resolve, reject) {
        if (age > 0) {
            resolve('Access allowed');
        } else {
            reject('Access denied');
        }
    });
}

checkAdult(-10)
    .then(
        res => console.log(res),
        err => console.log(err)
    )
    .then(() => console.log('Age verification complete'));