What causes the undefined error when a promise rejection is encountered?

I am currently working on a functionality involving checkboxes within a list. The goal is to display an alert message congratulating the user once they have selected 5 checkboxes. I am implementing validation using promises, however, I am encountering an issue. When I do not use the reject code, everything works fine. But when I include the reject code as shown below, it executes and displays an error as 'undefined'. Can you help me pinpoint where I may have made a mistake?

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

Answer №1

Remember, a promise can only be resolved once.

When you first toggle the checkbox, if you call reject() without passing any arguments, it will result in an error message of undefined.

Subsequent toggles of the checkbox will lead to calling either reject or resolve, but by then the promise will no longer be in a pending state.


Promises serve the purpose of notifying you of one result. They are not meant to handle multiple results.

In cases like this, where you require multiple results, it is more appropriate to use a standard event handler.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to load the center HTML element

So here's the plan: I wanted to create a simple static website with responsive images that load based on the browser width. I followed some suggestions from this link, but unfortunately, it didn't work for me. I tried all the answers and even a ...

Incorporate text into the URL of the image

Got a URL of an image like this: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg', and looking to add 240x240 within the URL. Current Url: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg Desire ...

Guide on adding a timestamp in an express js application

I attempted to add timestamps to all my requests by using morgan. Here is how I included it: if (process.env.NODE_ENV === 'development') { // Enable logger (morgan) app.use(morgan('common')); } After implementing this, the o ...

Instructions for removing a single key value pair from every object in an array and transferring it to a designated object within the same array

I need to update an array of objects by adding a key and value (e.g., age:15) to an object with the name email, while removing the age property from other objects in the array. [ { name: 'test', lname: 'last', age: 5 }, ...

Naming axes in Chart.js is a simple process that can easily be implemented

Greetings to all, I'm currently working on creating bar charts using chartjs...everything is going smoothly except for one thing - I am struggling to find a clean way to name my axes without resorting to CSS tricks like absolute positioning. Take a ...

What term is used to describe this in recursion?

I am trying to understand the concept of reversing a linked list and I stumbled upon a peculiar scenario in which a recursive function doesn't "return" but instead just calls itself. It seems that the function processes data backwards after the recurs ...

Is there a way for me to retrieve the variables saved within this array in JavaScript (vue.js)?

I'm currently working on a project involving the JavaScript Vue.js Framework. I've encountered an issue that I need help with, and I've included some code below to illustrate my problem. In the code, I have two variables in the data section ...

Pointer Permissions parsing does not permit creation

Despite meticulously following the instructions in this guide, I am encountering a 403 error when attempting to create a new row: Error code: 119 Error message: "This user does not have permission to carry out the create operation on Messages. This s ...

Tips for concealing a div in JavaScript when other divs are not present

Is there a way to hide the title div if related divs are not present in the HTML structure? This is the main HTML structure: <div class="row parent"> <div id="title-1" class='col-12 prov-title'> <h2 ...

How to iterate over an array and assign values to distinct labels using AngularJS

Challenge My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data. Each label is unique and w ...

At runtime, the array inexplicably becomes null

Having recently ventured into the world of Ionic framework development, I have encountered a puzzling issue. At runtime, an array inexplicably gets nulled and I am struggling to pinpoint the root cause. export interface Days { name:string; } @Compon ...

Grabbing an element with Cheerio in Node.JS

Struggling to extract the price element from this page: Running the console.log returns nothing, even though I'm certain I'm targeting the correct element. Any advice on how to tackle this issue? var request = require('request'); var ...

Angular HttpClient does not support cross-domain POST requests, unlike jQuery which does

I am transitioning to Angular 13 and I want to switch from using jQuery.ajax to HttpClient. The jquery code below is currently functional: function asyncAjax(url: any){ return new Promise(function(resolve, reject) { $.ajax({ type: ...

Methods for bypassing a constructor in programming

I am working on a code where I need to define a class called programmer that inherits from the employee class. The employee class constructor should have 4 parameters, and the programmer class constructor needs to have 5 parameters - 4 from the employee c ...

"Need to remove all chosen selections within an ng-repeat loop? Here's how

var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.cars = [{ model: "Ford Mustang", color: "red" }, { model: "Fiat 500", color: "white" }, { model: " ...

How to round whole numbers to whole numbers using JavaScript?

Looking to manipulate some numbers in JavaScript. Let's say we have x = 320232, y = 2301, and z = 12020305. The goal is to round these numbers to the nearest tens, hundreds, or thousands place. Thus, we want them to become x = 320000, y = 2300, and z ...

Node.Js error: "The requested resource does not have the 'Access-Control-Allow-Origin' header present."

This particular query shares similarities with others, however there is a perplexing difference that is causing it to malfunction. Previously, my JavaScript was able to fetch 6 json files without any issues. In Node.JS, I have configured cors and headers ...

Choose a random cell in Jquery every second

I am searching for a method to choose one div out of sixteen and change its CSS backgrounds. This selection needs to occur every second, so a new div is selected from the group each second. I am struggling with implementing the "every second" functionalit ...

Ways to call a DIV element in a PHP file from a different PHP file

I am facing an issue with referring to a specific <div> element from one .php page to another. The current code is redirecting me to the home page of the first page, instead of displaying the desired content. Can anyone provide guidance on how to ach ...

Display map.svg on the browser and execute a function when any area is clicked

Creating an online parking system that is compatible with desktop, iPad, and Android devices is my current project. I have a .svg formatted map for the parking area. I am looking for advice on how to display this map in a browser and execute JavaScript fu ...