javascriptecmascript-6es6-promisechain

How to make a chain of conditions for a Promise


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:

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


Solution

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