Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise:

  public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> {
    return this.$q((resolve, reject) => {
      let num: number;
      let month: number;
      let tempDate: Date;
      let deadline: Date = new Date(searchparam.start_date);
      let periodicity: Date = new Date(searchparam.start_date);

      if (searchparam.periodicity === 'onemonth') { num = (i * 1); month = 1; } else if (searchparam.periodicity === 'twomonth') { num = (i * 2); month = 2; } else if (searchparam.periodicity === 'threemonth') { num = (i * 3); }
      if (searchparam.periodicity === '14') {
        resolve(() => {
          futercampaign.start_date = new Date(periodicity.setDate(periodicity.getDate() + (searchparam.periodicity * i)));

          /* Storing the start_date temporarily */
          tempDate = new Date(futercampaign.start_date);

          /* Calculating the End Date */
          futercampaign.end_date = new Date(tempDate.setDate(tempDate.getDate() + searchparam.periodicity));
        })
      } else {
        resolve(() => {
          futercampaign.start_date = new Date(periodicity.setMonth(periodicity.getMonth() + num));

          /* Storing the start_date temporarily */
          tempDate = new Date(futercampaign.start_date);

          /* Calculating the End Date */
          futercampaign.end_date = new Date(tempDate.getFullYear(), tempDate.getMonth() + month, 0);
        })
      }
      /* Calculating the Deadline */
      futercampaign.deadline = new Date(tempDate.setDate(tempDate.getDate() - searchparam.deadline));

      return futercampaign;

    });

  }

This function is being used in another method:

      public generateCampaigns(campaing: any, searchparam: any, ev: any): void {

        for (let i: number = 0; i < searchparam.number_campaigns; i++) {
          if (validapps[i]) {
            let copy: any = angular.copy(campaign);
            this.DatesGenerator(copy, searchparam, i).then(()=>{
            if (!searchparam.wildcard) {
              copy.application = validapps[i];
              copy.os = validapps[i].os[0];
              copy.version_app = copy.os.version[0];
              copy.campaing_code = validapps[i].application_code;
            }
            this.suggescampaigns.push(copy);
            });
          }
        }
      }

However, when I call the second function, it gives an error saying that tempDate is undefined and I'm not sure why. Can somebody please help me with this issue?

Answer №1

The issue lies in the fact that tempDate is undefined at the moment you are trying to use it in this specific line of code:

futercampaign.deadline = new Date(tempDate.setDate(tempDate.getDate() - searchparam.deadline));

What you need to do is wait for tempDate to be resolved before utilizing it. This can be accomplished by setting futercampaign.deadline inside the resolves function of DatesGenerator and then returning futercampaign as the promise's resolution.

Answer №2

The issue arises due to the fact that the code within the calls to resolve is not executed until after your function finishes execution. This means that when you try to access the uninitialized tempDate variable at the end of the function, it has not been initialized yet. The code inside the this.$q() method will be executed at a later time, potentially after your second function has already completed.

I'm puzzled as to why you are using a promise in this scenario since the code is synchronous. Promises are typically used for asynchronous code. It might be best to remove the promise wrapping altogether and simplify your code for better results.

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

Adding a button to a shadow root that already exists is not the proper procedure

var shadow = document.getElementById( "3rd-party-div" ).shadowRoot; let style = document.createElement("style"); style.textContent = ` .custom_button{ padding: 10px; display:block; float:left; text-ali ...

The CanJS model is unable to retrieve data from a .json file

Implementing MVC using AMD in canjs with requirejs has been my current focus. Here's a look at my domains.json file: [ "1":{"uid": "1","urls": "domain1.abc.com"}, "2":{"uid": "2","urls": "domain2.abc.com"}, "3":{"uid": "3","urls ...

Inserting a line break in real-time within a JSX statement

Currently working on a React application that retrieves song lyrics from an API. The API provides me with a lyrics_body attribute as a string, which I use to showcase the lyrics on the webpage. However, when React renders it, the format is not ideal becau ...

Navigating a webpage with Material select and routerLink in Angular 6

I am currently developing a feature that allows users to navigate to a page to access a list of documents from a policy. In addition, I am incorporating all policies so that users can easily move between them using a select form and direct you to the selec ...

Troubleshooting compatibility issues between jQuery scrollLeft and Angular

As I attempt to programmatically scroll a horizontally overflowing div, I am confident that my final code should resemble the following: var $element = $('#widgetRow');//or maybe $('#widgetRow').parent(); //With 1 or more parent()& ...

Validation in PHP and Javascript is only partially effective

I encountered an issue with my form validation setup that utilizes JavaScript, Ajax, and PHP. While the errors are correctly displayed when the form is filled incorrectly, I am unable to submit the form even if there are no errors. Clicking the submit butt ...

How can I transfer a PHP variable into a JavaScript variable nested within another PHP variable

After my php/html script generates the image, I am looking to display it without needing to reload the page. I currently call a javascript function within the PHP code to change the image. However, I am unsure how to pass the new image name to this javasc ...

Displaying data issue with Typescript typed array

While working with Angular 7 and Typescript 3, I encountered an issue where I was trying to pre-populate an array of ingredients in a service for use in a component. However, when I checked the console output, the array was showing empty objects. If I ini ...

A guide on implementing directives in Angular 2

I am trying to load my navbar.html in my app.component.html by using directives and following the method below: Here is my navbar html: <p>Hi, I am a pen</p> This is my navbar.ts: import {Component, Directive, OnInit} from '@angular/c ...

Troubleshooting React's failure to start with node.js running behind an Nginx Reverse Proxy

This is my first attempt at setting up a Node.js server in production (other than one Meteor server), and I've run into a problem that I can't figure out on my own. I have built an application using React. Here is the server code: // Imports va ...

Challenges with form validation

Hello everyone, I'm a newbie to JS and struggling with my code. It seems like everything should work, but it just won't. The issue seems to be with the phone number form validation. I've written code that, in theory, should do the job, but ...

The undefined dispatch function issue occurs when trying to pass parameters from a child component to React

There is an action that needs to be handled. It involves saving a new task with its name and description through an API call. export const saveNewTask = (taskName, taskDescription) => async dispatch => { console.log(taskName, taskDescription); c ...

How to enhance a jQuery tab control by implementing custom JavaScript forward and back arrows?

Although there are other questions related to this topic, mine is unique. I have a scrolling jQuery feature that utilizes tabs for selection and is automated. Modifying the layout is challenging because it is dynamic and depends on the number of items in t ...

How to effectively create factories in AngularJS

I stumbled upon this angularjs styleguide that I want to follow: https://github.com/johnpapa/angular-styleguide#factories Now, I'm trying to write my code in a similar way. Here is my current factory implementation: .factory('Noty',functi ...

Validating date inputs with ng-change in AngularJS

I am currently utilizing AngularJS along with AngularJS bootstrap within my webpage. One of the components I have is a date picker directive that is structured like this: <div class="form-group {{dateStatus.class}}"> <p class="input-g ...

Generate a responsive list with a pop-up feature under each item (using Vue.js)

Currently, I believe that Vue may not be necessary since most tasks can be done using JavaScript and CSS. I am attempting to design a list layout as follows: [A] [B] [C] [D] When an item is clicked, the information about that specific item should ...

Better ways to conceal notifications as soon as a new one appears with Toastr

Whenever a new notification pops up in my application, I desire for the previous one to automatically disappear. It is crucial for only one notification to be displayed at any given time. Is there a way to accomplish this using toastr? ...

What is the best way to retrieve the value from a Material UI textfield after hitting the enter key

Having trouble retrieving input values with the provided code. Attempted using onKeyUp, onKeyDown, and onKeyPress, but none of them returned the value as desired. Typically, I would use the onChange property to get the value, but it triggers for every ne ...

Encountered an error when attempting to use 'appendChild' on 'Node': the first parameter is not the correct type. It was able to work with some elements, but not with others

I'm currently working on a script that utilizes fetch to retrieve an external HTML file. The goal is to perform some operations to create two HTMLCollections and then iterate over them to display a div containing one element from each collection. Here ...

What strategies can I implement to reduce the size of my Angular application to 500K or less?

I have been researching ways to reduce the size of my Angular application, but have not yet found a solution that significantly decreases its size. Currently, my application is 4M in production and 14M in development. So far, I have tried: Lazily loadin ...