Learn how to efficiently process a data queue with AngularJS using Promises

Within my AngularJS application, I have a Service and multiple controllers running simultaneously. The app receives data updates from the server in JSON format through the Angular Service. To manage the vast amount of data, I need to queue it within the server and then process and distribute it to all the controllers using the registered controller callbacks.

The current queue of JSON Objects looks like this:

In ----> [Obj1] - [Obj2] - [Obj3] - [Obj4] ---> OUT

The input operation is asynchronous, with 'n' number of objects being added to the queue every second (which can also become empty).

I aim to dequeue one item at a time, process the JSON data, and continue this cycle until the last item in the queue is reached. Additionally, any new items added to the queue should be processed as well.

After researching, I discovered that AngularJS Promises could help achieve this task. However, as a newcomer to AngularJS, I'm struggling to grasp how to implement them effectively.

Some sources suggest using var deferred = $q.defer();, but I'm unclear on how to utilize $q and what distinguishes it from a traditional JavaScript Promise.

Are there simpler methods for implementing this functionality?

Sample code snippet:

angular.module('myApp')
.service('DataService', ['$rootScope', 'UpdateService', function($rootScope, UpdateService)
{
    // Array to store JSON updates    
    var arrayOfUpdates = [];

    // Array for storing callback functions to send processed updates 
    var arrayofCallbacks = [];

    // Method called upon receiving updates from "UpdateService" server 
    this.onDataUpdated = function (jsonObj)
    {
        // Add received object to the array
        arrayOfUpdates.unshift(jsonObj);
    }

    // Process and distribute data 
    function processData()
    {
         // Retrieve the last element from the array 
         var jsonObj = arrayOfUpdates.pop();

         // Process the JSON data - which takes 400-500 MS
         var data = doSomeCalculations(jsonObj); 

         // Multiple callbacks may exist -- This operation also takes time
         for(var index=0;index<arrayofCallbacks.length;index++)
         {
               var object = arrayofCallbacks[index]; 
               object.onUpdatedData(data);
         }       

         // After processing this item, dequeue the next element, process it, and send it to the registered callbacks 
         // Avoid calling "processData()" recursively to prevent loops or calling it during incomplete processing 
    }
});

Answer №1

If you're interested, consider exploring angular events by reading about Working with $scope.$emit and $scope.$on.

One approach is to subscribe in every controller and trigger an event after processing the data, which all controllers will then respond to.

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

Verify whether a variable includes the tag name "img."

Currently, I am working with a variable that holds user input in HTML format. This input may consist of either plain text or an image. I am looking to determine whether the user has entered an image or just simple text. Here is an example of user entry: t ...

The graph visualization fails to update properly even after attempting to redraw it

A new feature has been added to the website that allows users to zoom into specific areas of graphs created using Flot objects. An array containing all the Flot objects on the screen has been implemented, and the selection plugin is being used for this pur ...

How can you utilize a computed property in a Vue component to select all the text within it?

When using $event.target.select(), I usually can select all the text. However, in this scenario, it seems to be selecting everything and then replacing the selection with the computed property. How can I select all after the computed property has finished? ...

Linking the Twitter social button to the originating page

Is there a way to link the Twitter button to a referrer URL, so that all tweets will refer back to the page the visitor came from instead of the landing page itself? I've been able to do this with Facebook and G+ by using a href within the script and ...

Listen up, Javascript keyboard input recorder

I am aiming for the search bar to pop up when you type. The code below is functioning, but I am facing an issue where the search bar pops up even when typing in a different input field, such as the comment input. Is it feasible for the search bar not to ...

Bizarre Object notation with JavaScript

While browsing through a Library called WebApp.net, I stumbled upon this interesting piece of code: var $h = { get HEAD() { return 0 }, get BACK() { return 1 }, get HOME() { return 2 }, get LEFT() { return 3 }, get RIGHT() { return 4 } ...

Navigating to a parent URL where the Angular configuration is set can be achieved by following these steps

My application revolves around a webpage created with the use of node and angular. On the root URL (/), I have incorporated a signup and login form without the use of Angular. Upon successful login, Angular scripts and configuration files are loaded on the ...

Unable to resolve the issue within Angular UI modal

Currently, I am facing an issue with displaying a modal using Angular Bootstrap UI. The modal is supposed to resolve items in the controller, but I am struggling to access those resolved items in the modal controller. $scope.showItemsInBill = function(bill ...

Unleashing the Power of Dynamic JSON Data Access

I am facing an issue with my React Child component. Here is the code snippet: const SingleProject =(props)=>{ let data = projectData.VARIABLE_FROM_PROPS.projectDetails; let asideData = projectData.VARIABLE_FROM_PROPS.projectSideBar; useEffe ...

Crafting artistic shapes using the Canny Edge Detection technique on Canvas

Can someone provide some guidance on using Canny Edge Detection to generate shapes in Canvas? ...

Tips for Enhancing Window Leveling (Brightness and Contrast)

const pixelArray = [11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11..] if (pixelArray != null) { for (let i = 0; i < pixelArray.length; i++) { let ...

Adjusting iframe height based on its source URL using JQuery

Currently, I have implemented a script to adjust the height of YouTube iframes in order to maintain a 16:9 aspect ratio while keeping the width at 100% of the container. The challenge I am facing is ensuring that the script only affects YouTube videos and ...

I prefer to avoid using the "#" sign in URLs

<a href="#" onClick="load_page()">intro</a> I am trying to avoid displaying the # sign in the URL, and I would like it to appear like this instead: www.mydomain.com/ However, it currently displays as follows: www.mydomain.com/# Is there a ...

Is AngularJS $location.path the same as the current URL?

Is there a way to manually reload the page? I tried using $location.path('/account'); and it successfully redirected me to a different page. However, when I tried $location.path('/account/messages'); while already on /account/mess ...

What You See Is What You Get - A versatile tool for editing both text and

As a developer, I have encountered a common need that StackOverflow addresses. Situation I am in the process of creating a website where users can post code examples and articles using an admin system. These posts may be created by me or registered fron ...

Is there a way in Reactjs Material UI 5 (MUI5) to unselect only the star that was clicked, without affecting the rest of the stars in the

For instance: I selected the 3rd star on the rating component, but when I click on it again, all the previous stars disappear and it shows 0 stars. How can I make it so that if I click on the 3rd star a second time, only the 3rd star is removed, leaving ...

How to completely disable a DIV using Javascript/JQuery

Displayed below is a DIV containing various controls: <div id="buttonrow" class="buttonrow"> <div class="Add" title="Add"> <div class="AddButton"> <input id="images" name="images" title="Add Photos" ...

AngularJS, the element being referenced by the directive is empty

Currently, I am in the process of transferring a jQuery plugin to AngularJS simply for the enjoyment of it. Previously, when working with jQuery, my focus was on manipulating the DOM using jQuery functions within the plugin loading function. Now that I am ...

JavaScript: What is the best method for eliminating all square brackets from within the outer array?

let list = [ ["water", "earth"], [6, "light"], [32], ["fire", "air", 9] ]; The example provided shows the list made up of four elements, each being an array. Currently, the length of list is 4. I am curious if there is a way to eliminate all inner square ...

Angular: Issue with FormArrays not iterating properly

Apologies for the lengthy post, but I needed to provide a detailed explanation of the issue I am facing. In my form, there is a control that contains an array of JSON data. I have created a reactive form based on this structure. Below are the JSON data an ...