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

Uploading files with Angular and NodeJS

I am attempting to achieve the following: When a client submits a form, they include their CV AngularJS sends all the form data (including CV) to the Node server Node then saves the CV on the server However, I am encountering difficulties with this proc ...

An error with expanding nodes in the Angular-Kendo UI treeview

I have encountered a potential bug with the Kendo UI treeview in the Angular version that seems to be specific to the k-template option. The bug can be observed on their demo page here: If you expand Item 2, you will notice that the text suddenly changes ...

jqGrid display/hide columns options dialogue box

I am looking to implement a feature that allows users to toggle columns in my jqGrid. I came across a module for this purpose, but unfortunately, it is no longer supported in jqGrid 4.x. I have searched for a replacement module without success. Are there ...

Displaying live data from a spreadsheet directly on a sidebar

My goal is to extract data from another sheet in the same spreadsheet and present it as a dropdown selection in the sidebar. The code.gs file contains a function called getVisualData() that successfully retrieves the desired list: function getVisualData() ...

Initiate an Ajax request from a hyperlink

Is it possible to trigger an Ajax request from a hyperlink? I am interested in updating the inner html of a div element upon clicking on a hyperlink through JavaScript. ...

What is the best way to transfer an array made in JavaScript to a different JSP and subsequently utilize that array in a Java function within that JSP?

I have a script that needs to pass an array called "playernames" to a Java function on another .jsp. I'm looking for guidance on how to send this array to the other page and then retrieve it for my Java function. <script> function getPlayerName ...

Disregard the sorting of rows in the MUI Datagrid

Any advice on excluding the "TOTAL" row from sorting in MUI library? onSortModelChange={(test, neww) => { neww.api.state.sorting.sortedRows = [14881337, 2, 3] neww.api.setState({...neww.api.state}) } } Review ...

The attributes `ng-class` and `class` are used to apply CSS styles

Can you provide guidance on when to use one method over the other for HTML elements such as div, span, and tables? Is it advisable to mix both methods or could it potentially cause some issues? ...

Is there a way to automatically update the URL to include $_GET['data'] (media.php?data=123) when a selection is made from a dropdown list?

I'm currently working on a project that involves a website in PHP and a MySQL database. I have successfully linked the two together, and now I have a combobox filled with data from the database. Below is my script for handling the selection: <scr ...

Adding external JavaScript files that rely on jQuery to a ReactJS project

As a beginner in web development, I have a question regarding importing external JavaScript files in ReactJS. I currently have the following imports: import $ from 'jquery'; window.jQuery = $; window.$ = $; global.jQuery = $; import './asse ...

Resolving the name error: Importing definition files from node_modules/@types in Angular

After acquiring this set of definitions from a node_modules/@types file, I encountered an issue trying to import it into my js file. I went ahead and executed npm install @types/p5 before including it in my tsconfig.json as follows: "types": [ "n ...

Referencing an object by using a variable containing its name

I need a way to reference an object using a variable with its name in it. I've figured out how to do this for properties and sub-properties: var req = {body: {jobID: 12}}; console.log(req.body.jobID); //12 var subProperty = "jobID"; cons ...

Is it possible to extract tooltip text from a website using Python and Selenium, specifically when the text is generated by JavaScript?

Can anyone help me retrieve the tooltip text that appears when I hover over the time indicating how long ago a game was played? You can find my summoner profile here. I have noticed that the tooltip text is not visible in the HTML code and suspect it may ...

Step-by-step guide on how to prioritize rendering the login page before the ngView in AngularJS in order to

As I begin my journey with Angular JS, I am eager to implement security measures in my application. My intention is to set up a log-in page as the default landing page for my single page application. Can anyone provide guidance or recommendations on how ...

Upon clicking, the input texts revert to their original default values

I have a form below that is working as intended, except for one issue. When I click the 'Add' link, the texts in all the textboxes revert to their default values, as shown in the images. How can I resolve this problem? Thank you. before click: ...

Show detailed information in a pop-up window

Javascript $(function() { var dmJSON = "clues.json"; $.getJSON( dmJSON, function(data) { var idx=1; $.each(data.details, function(i, f) { var myid = 'mypop'+String(idx); idx++; var $popup="<popu ...

Color in the diamond shape only to a designated height

I am in search of a unique diamond shape that allows me to fill the color up to a specific height based on an attribute or variable provided. https://i.stack.imgur.com/62U6h.png. I attempted creating the diamond shape and initially considered placing it ...

Creating dynamic elements in JavaScript and assigning them unique IDs

Hi there, I'm currently working on a project that requires generating dynamic divs with a textbox and delete button inside each one. The challenge I'm facing is figuring out how to assign a unique ID to each textbox element so that I can properly ...

Is there a way to update the color of a different AngularJS material button when a user selects one button?

I have two buttons on the screen. When the user clicks button 1, an HTML form is displayed. At that point, I want to change the color of the other button to an AngularJS Material button (Button). I've tried some examples but haven't been successf ...

Error: The parent class is not defined as an object

My program is currently attempting to utilize this.state, but I encountered an error. Can anyone provide assistance on resolving this issue? https://i.stack.imgur.com/wgxBf.png ...