The recursive JavaScript function is not returning as expected when using defer

Having an issue with a recursive function. It appears to loop through effectively when the data return is null, but it fails to return the promise correctly when the data is not null after completing the recursive task. It seems like the promise gets lost somewhere upon finishing the recursive process. Can anyone help me identify what I might have done wrong here?

var callrq1 = function(globalsystemid, globalgraphid, start, end, lastcheck) {
  var datetimeformat = "YYYY-MM-DD HH:mm:ss";
  var d1 = new $.Deferred();
  var request1 = "../system/" + globalsystemid + "/highcharts.xml?type=" + globalgraphid + "&start=" + start + "&end=" + end;
  var requeststring1 = makejson(request1); //this makejson method performs ajax get and returns a promise
  requeststring1.done(function(data) {
    if (data != null) {
      d1.resolve(data);
    } else {
      var theend = moment(lastcheck).format(datetimeformat);
      var newstart = moment(end).format(datetimeformat);
      var newend = moment(end).add(1, 'weeks').format(datetimeformat);
      if (newend <= theend) {
        //recursive callrq1
        callrq1(globalsystemid, globalgraphid, newstart, newend, theend);
      } else {
        d1.resolve(null);
      }
    }
  });
  return d1.promise();
}

callrq1(globalsystemid, globalgraphid, starttimeobj.start, starttimeobj.end, endtimeobj.start).then(function(data) {
  console.log(data);
});

Answer №1

You overlooked handling the deferred in the event of the recursive call. However, it's advisable not to utilize a deferred for this purpose! Rather, you should link a then callback and return the resulting promise from your function. It is even possible to return promises from the callback, as demonstrated in the recursive scenario:

function fetchData(globalsystemid, globalgraphid, start, end, lastcheck) {
  var datetimeFormat = "YYYY-MM-DD HH:mm:ss";
  var requestURL = "../system/" + globalsystemid + "/highcharts.xml?type=" + globalgraphid + "&start=" + start + "&end=" + end;
  var requestData = makeJSON(requestURL); // The makeJSON function performs an AJAX GET and returns a promise
  return requestData.then(function(response) {
//^^^^^^                ^^^^
    if (response != null) {
      return response;
//    ^^^^^^
    } else {
      var endDate = moment(lastcheck).format(datetimeFormat);
      var newStartDate = moment(end).format(datetimeFormat);
      var newEndDate = moment(end).add(1, 'weeks').format(datetimeFormat);
      if (newEndDate <= endDate) {
        return fetchData(globalsystemid, globalgraphid, newStartDate, newEndDate, endDate);
//      ^^^^^^
      } else {
        return null;
//      ^^^^^^
      }
    }
  });
}

Answer №2

Failure to resolve the deferred during recursion

var callrq1 = function (globalsystemid, globalgraphid, start, end, lastcheck) {
    var datetimeformat = "YYYY-MM-DD HH:mm:ss";
    var d1 = new $.Deferred();
    var request1 = "../system/" + globalsystemid + "/highcharts.xml?type=" + globalgraphid + "&start=" + start + "&end=" + end;
    var requeststring1 = makejson(request1); //this makejson function is an ajax get and return promise
    requeststring1.done(function (data) {
        if (data != null) {
            d1.resolve(data);
        } else {
            var theend = moment(lastcheck).format(datetimeformat);
            var newstart = moment(end).format(datetimeformat);
            var newend = moment(end).add(1, 'weeks').format(datetimeformat);
            if (newend <= theend) {
                //perform recursive callrq1
                callrq1(globalsystemid, globalgraphid, newstart, newend, theend).done(function(data){
                    d1.resolve(data);//provide any necessary data
                });
            } else {
                d1.resolve(null);
            }
        }
    });
    return d1.promise();
}

callrq1(globalsystemid, globalgraphid, starttimeobj.start, starttimeobj.end, endtimeobj.start).then(function (data) {
    console.log(data);
});

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

Developing an Angular 2 Cordova plugin

Currently, I am in the process of developing a Cordova plugin for Ionic 2. The plugin is supposed to retrieve data from an Android device and display it either on the console or as an alert. However, I am facing difficulty in displaying this data on the HT ...

How to Display a Modal Window Automatically Using Bootstrap.js?

Recently, I've become interested in using the Bootstrap library by Twitter for my simple web page. My goal is to have a modal window automatically display after the page loads. If anyone has any tips on how to achieve this, I would greatly appreciate ...

Show users who liked a post from 2 different collections in Meteor

How do I retrieve a list of users who have "liked" this post from a collection and display it in a template? Collections: likes: { "_id": 1234, "userId": "1dsaf8sd2", "postId": "123445" }, { "_id": 1235, "userId": "23f4g4e4", "pos ...

Prevent redirection when submitting and show an error message instead

I implemented a login system where, upon entering the correct username and password, a token is stored in local storage. If there's an error with the credentials, an "Login Unsuccessful" message is displayed. Everything was functioning correctly until ...

Can an HTML DOM object be converted to a JSON string using JSON.stringify in JavaScript?

Trying to fetch an external HTML file and convert its body content into a string has been giving me unexpected results. Is there a way to achieve this successfully? var xhr = new XMLHttpRequest(); function loadFile(){ xhr.open("GET", 'index.html ...

Tips on altering the input content in React Js?

I am currently working on developing a component for my application where I want to create a button that, when clicked, opens an input field. After entering text into the input field and clicking the button again, another input field should appear, and so ...

Ajax not functioning properly on desktop browsers but successfully operating on Android devices

I have encountered an issue where I can run this code in an Android app (using PhoneGap and jQuery Mobile) but not on desktop browsers. It triggers a syntax error in Firebug specifically for this line: var TicketList = eval("(" + ajax.responseText + ")"); ...

The functionality of my Javascript code is restricted to a single element within a Python embedded for loop in Django2

My Python for loop is iterating through these HTML template cards, each accompanied by JavaScript. However, I'm encountering an issue where the JavaScript only seems to work on the first element (specifically, it's meant to retrieve the seeked po ...

Implementing a dynamic update of an HTML element's content with JSON data - Learn how!

My task involves creating a quiz application where I need to show the answers along with images of the choices stored in my JSON data. However, I encounter an error: Uncaught TypeError: Cannot set properties of null (setting 'src') when I attempt ...

Jquery auto-suggest form validator

I have implemented a search dropdown menu using jQuery. Everything is working fine, and the 'not match' message displays properly when entering data that does not match any items. However, if I select an item from the dropdown and then modify it ...

Displaying a random div using javascript

Seeking a way to display random divs on my webpage, I came across a stackoverflow solution: Showing random divs using Jquery The recommended code can be found here: http://jsfiddle.net/nick_craver/RJMhT/ Despite following the provided instructions, I am ...

Obtain JSON data response in PHP with the help of jQuery

Below is the code I am using to make an AJAX call and retrieve data from another PHP file: $.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km}, function(data){ $('#fare'). ...

The discrepancy between the heights of a div using Jquery and JavaScript

There is a container div encompassing all the site's content, which dynamically stretches. Additionally, there are multiple other divs that also stretch using the same method as in 20 other sites. Despite trying various methods with jQuery and JavaSc ...

Setting up a Bootstrap tokenfield for usage with a textarea

I was attempting to set up a tokenfield on a textarea with increased height, but it is showing up as a single-line textbox. How can I modify the tokenfield to function properly with a textarea? <textarea name="f1_email" placeholder="Enter Friends' ...

When the initial image URL returns a 404 error, the ng-src path does not automatically switch to the alternative

I'm currently working on a webpage where I want to show an image only if the URL of that image is valid, using AngularJS. The challenge I'm facing is that ngIf only checks whether a value is null or not. So, even if the URL returns a 404 error, ...

What is the best way to position the list element to align with the top of a div container?

To see a live example, visit this link. My goal is to create a line that separates two li elements within a nested ul. However, the line ends up taking the width of the container ul instead of the div containing the entire structure. In the provided examp ...

The 404 error is handled by the express application before continuing to other routes. Some routes may not be recognized by the express.Router module

Shown below is the content of app.js: var express = require('express'); var routes = require('./routes/index'); app = express(); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next ...

Updating the DOM does not occur by simply adding an object to the Array; instead, the database is updated once the data has

My database has verified data that is being updated, however, the DOM is not reflecting these updates. <ul> <li ng-repeat="aReview in reviewList"> .... .... </li> </ul> <script> if(globalMethods.stringVa ...

JavaScript and modifying the attributes of the nth child

I'm working on a navigation bar that changes the "background-image" of menu items using the nth-of-type CSS selector. Now, I need to figure out how to dynamically change the picture of the "background-image" when hovering over a specific menu item usi ...

cracking reCAPTCHA without needing to click a button or submit a form (utilizing callback functions)

Currently, I am facing a challenge with solving a reCaptcha on a specific website that I am trying to extract data from. Typically, the process involves locating the captcha inside a form, sending the captcha data to a captcha-solving API (I'm using ...