Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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);
  });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!