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
}
});