Search code examples
javascriptpromiseunhandled-promise-rejection

Why Reject of Promise giving undefined error?


I have a set of list with checkboxes, when I click 5 checkboxes an alert message to be displayed congrates you have selected 5 options. I have to do the validation using promise. If I am not using reject, it is working fine. But if I add the code as given below, 'reject' code is executed and displaying error as 'undefined'. Where have I gone wrong?

let clickvalidation = new Promise(function(resolve, reject) {
  $('input[type=checkbox][id=chk1]').change(function() {
    if ($(this).is(':checked')) {
      noOfClick++;
      if (noOfClick == 5) {
        resolve();
      } else {
        reject();
      }
    }
  });
});

clickvalidation
  .then(function() {
    console.log('Success, You are a GEEK');
    alert(`Congrats 5 tasks have been successfully completed`);

  })
  .catch(function(e) {
    console.log(e.stack);
  });

Solution

  • A promise can only resolve once.

    The first time you change the checkbox, you call reject() and you don't pass it any arguments (so it errors with an undefined message).

    Any subsequent time you change the checkbox, you call reject or resolve but the promise is no longer pending.


    Promises are a good tool to tell you when you have a result. They aren't designed to provide multiple results.

    This isn't a situation where promises are a useful tool. Just use a regular event handler by itself.

    let counter = 0;
    
    document.querySelector('input').addEventListener('change', () => {
      counter += 1;
    });
    
    document.querySelector('button').addEventListener('click', () => {
      if (counter === 5) {
        console.log("OK");
      } else {
        console.log("Not OK");
      }
    });
    <input type="checkbox"><button>OK</button>