Async Recursive Function

I am facing a challenge with my project. My framework of choice is AngularJS and I do not have access to jQuery or Lodash.

The Issue

In my code, I have a function named "refresh". This function initiates an asynchronous call using angular $http to retrieve new data from the server. The server provides 25 new updates starting from the specified date. To fetch all the new messages, I need to continuously make requests to the server (updating the "updateDate" each time I receive new data) until there are no more messages (empty array).

Example Code

$scope.refresh = function () {
    var date = new Date();

    $http({
        method: 'GET',
        url: 'http://path.to.my.server',
        timeout: 6000
    }).then(function (success) {  
        date = success.date[0].date;                     
        callback(success.data);       
        //Data manipulation
    }, function (error) {
        console.error("Could not retrieve new messages: \n", error.data);
        errcallback(error);
    });
}

Attempts Made

I attempted to separate the request into a different function and call it multiple times as you would with a standard async function.

I also tried utilizing a while loop and using a boolean variable to indicate when data collection is complete. However, the issue with a while loop is that it does not wait for the call to finish, resulting in a potentially infinite loop that could crash the program.

Considering using a for loop, but unsure about the number of iterations required. It might be just one, but it could also be five or even more.

I understand how recursive functions operate, but implementing an async recursive function is where I face difficulty. Any suggestions or solutions are highly appreciated. (If there's an alternative approach that doesn't involve recursion, I'm open to exploring that as well)

Answer №1

When it comes to making async functions recursive, the key advantage is that you don't have to worry about stacking issues.

To implement this approach, simply create a function for your ajax call and let it recursively call itself until it has gathered all the necessary data:

$scope.refresh = function () {
    var date = new Date();
    var results = [];

    gather();

    function gather() {
        $http({
            method: 'GET',
            url: 'http://path.to.my.server',
            timeout: 6000
            // using `date` here
        }).then(function(success) {
            date = success.data[0].date;                    
            if (thereAreNewResults) {
                results.push.apply(results, success.data);
                gather();
            } else {
                callback(results);       
            }
        }, function (error) {
            console.error("Could not retrieve new messages: \n", error.data);
            errcallback(error);
        });
    }
};

This code snippet serves as a starting point rather than providing a complete solution. Feel free to customize it according to your specific requirements.

Take note of my if(thereAreNewResults). While I initially thought if(success.data.length) would be more appropriate, your question implied there will always be at least one row of data, so adjust accordingly.

Answer №2

I plan to create a recursive function that will fetch the data:

$scope.fetchData = function () {

    $scope.allData = [];

    var getData = function(currentDate){   
        $http({
            method: 'GET',
            url: 'http://my.server.path'+/ currentDate , // make sure to format the date correctly
            timeout: 6000
        }).then(function (success) {  
            currentDate = success.date[0].date; //assuming 0 is always the most recent message                
            //Perform operations on the data; all of it will be accessible in $scope.allData
            $scope.allData = $scope.allData.concat(success.data);     
            // should we call the function again? 
            if( /* add condition to determine when to stop fetching data */ ){
                getData(currentDate);
            }
        }, function (error) {
            console.error("Could not fetch new messages: \n", error.data);
            errcallback(error);
        });
    }

    var currentDate = new Date();
    // initiate the function
    getData(currentDate);  
}

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

Is it possible to establish restrictions on file uploads using Firebase authentication and storage without the need for an intermediary server?

Currently diving into the world of Firebase authentication and storage within a web application. My concept involves prompting users to log in using Firebase credentials and then proceed to upload an image. While exploring Firebase auth and storage capabi ...

What is the process for validating a jQuery/AJAX form?

Can someone help me with validating my sign-up form? Even when there is no data entered, it still gets added to the database whenever the submit button is pressed. Here's my current code: <form id="signupform" class="form" method="post" action="#" ...

Setting the default typing language in Protractor: A step-by-step guide

Is there a way to specify a default typing language in my configuration file? While running test cases locally, I am unable to switch keyboard languages during execution as it impacts the typing language for Protractor causing the tests to fail. If you h ...

What is the best way to duplicate a set of objects in ThreeJS?

I am trying to develop an educational activity for my students wherein a group of objects needs to be replicated and positioned randomly in a scene. I have created a function for this purpose, but unfortunately, it only duplicates the same object instead o ...

Trigger a popup notification with JavaScript when

Check out this snippet of code: <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/ ...

"Creating dynamic movement for a collection of layered images through asynchronous operations in JavaScript: A step

I have a collection of 10 shapes that together form an intricate square image, depicted in the diagram below. My goal is to animate each shape by utilizing the output of a periodic function such as sine, which would dynamically respond to the user's m ...

Using a Key to Activate the Trigger Button Instead of a Mouse Click

I am seeking assistance with a specific issue. I currently have a timer with a stop button that can be clicked with a mouse, but I want to enable the button to also be activated via a key press. I have attempted different methods such as using document.add ...

The command "npm run build" is not running successfully, likely due to npm not being able to interpret ES6 syntax

I am currently developing a web application using Vue.js and Flask. While I can successfully compile the Vue app on my laptop by running npm run build and integrating the static files into my Flask app, I encounter an issue when attempting to do this on a ...

Dealing with unexpected errors that occur and are displayed in the browser's console when using AngularJS

Is there a way to manage unexpected exceptions that are outputted to the browser console? I would like to log these exceptions to a method within my Angular controller or service. Can this be achieved using $exceptionHandler? If so, can you recommend a s ...

Switching up the content of an HTML page with JavaScript or JQuery: what you need

Is it possible to update HTML content using JavaScript or JQuery? https://i.sstatic.net/EWOXg.png I am trying to change the contents from 1 to 5 in a sequential order based on the time shown in the image. How can I achieve this using JavaScript or JQuery ...

Engaging with Electron through an HTML file

Forgive my lack of experience, but I'm diving into the world of Electron and feeling a bit overwhelmed. Here's a snapshot of what I've got so far in my project: package.json: ... "main": "main.js", "scripts": { "start": "electron ." } . ...

Unable to halt ajax request by pressing cancel button

There's a jQuery script that I have implemented. When a button is clicked, it triggers an AJAX function to count the number of rows from a specific query and stores the result in a jQuery variable upon successful completion. Subsequently, another AJA ...

What is the process of compiling TypeScript code?

When attempting to use tsc, I encountered issues. Even when having typescript but lacking tsc, the problem persisted. What steps should I take next? https://i.sstatic.net/Djgqb.png ...

Angular enables draggable and resizable components

Are there any Angular equivalents to the great draggable and resizable widgets offered by jQueryUI? I am looking for alternatives to using jQueryUI. Is it possible to make my modal draggable and resizable without relying on jQueryUI? ...

Executing a nested function before moving on to the subsequent code statements

I have a requirement where certain functions in my codebase need to check if a user is logged in before proceeding. Instead of duplicating this check logic, I want to call a single getUser() function each time. Here is the order of operations for the func ...

When decoding a JWT, it may return the value of "[object Object]"

Having some trouble decoding a JSON web token that's being sent to my REST API server. I can't seem to access the _id property within the web token. Below is the code I'm currently using: jwt.verify(token, process.env.TOKEN_SECRET, { comp ...

The computed value in Vue.js does not execute during initialization

Every time my vm is created, the computed values get function fails to run, leaving the value unassigned. Oddly enough, it does run when I attempt to access the value, just not during the initial app startup. Essentially, the goal is to calculate the ski ...

Finding the Ideal Location for Controllers in an Express.js Project

I'm relatively new to software development and one concept that I find challenging is organizing the directory structure of various projects. As I prepare to embark on an Express project, I prefer keeping controller classes separate from route callbac ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

Issue encountered while generating JSON in PHP

I'm working on fetching data from a MySQL database in PHP and then returning it in JSON format to an Angular controller. However, I'm facing an issue where some unwanted strings are being appended during the JSON creation process. This is causin ...