In my AngularJS app I have a Service
and multiple controllers
running at a time. App receives data updates from server (in form of JSON) in the Angular Service
. I need to queue this data in the server (as data is vast in amount) and then after some processing service needs to send this data to all the controllers using the controller callbacks registered with service. Controllers further process this data.
I have below queue of JSON Objects:
In ----> [Obj1] - [Obj2] - [Obj3] - [Obj4] ---> OUT
The Input operation is asynchronous and there are 'n' number of objects getting added in the queue every second (queue can also become empty).
I need to pop one item at a time and then process the received JSON data, this process will go on till last item in the queue. also as new items are added in the queue they will be processed.
From some of the posts I got to know that this can be done using AngularJS Promise, but as I am completely new to Angular I am not able to understand how it can be implemented.
Also in some examples it is mentioned to use var deferred = $q.defer();
, so how to use $q
and what is the difference in $q
and Promise
?
Also is there other "simple" way of implementing this functionality?
Example code:
angular.module('myApp')
.service('DataService', ['$rootScope', 'UpdateService', function($rootScope, UpdateService)
{
// To store array of JSON updates
var arrayOfUpdates = [];
// To store callbacks to which we need to send updates after processing
var arrayofCallbacks = [];
// Method is getting called when there are updates from "UpdateService" server
this.onDataUpdated = function (jsonObj)
{
// This will add this object in the array
arrayOfUpdates.unshift(jsonObj);
}
// This method will process data and send it further
function processData()
{
// Get the last element from the array
var jsonObj = arrayOfUpdates.pop();
// Now process this JSON data - this method takes time 400-500 MS
var data = doSomeCalculations(jsonObj);
// There can be 10-20 callbacks at a time -- This also takes time
for(var index=0;index<arrayofCallbacks.length;index++)
{
var object = arrayofCallbacks[index];
object.onUpdatedData(data);
}
// After processing this item
// Pop next element and process and send to registered callbacks
// I can not call "processData()" again as it can create loop
// Also calling it after interval (using $interval) might call it when it has not completed processing
}
});