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
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'));