logo

Premium Support
24/7/365

Premium support customers may submit help-desk tickets using the form below.
Alternatively, the help-desk system can be accessed directly at support.maxiomtech.com. support@maxiomtech.com
info@maxiomtech.com
+1 (703) 942-9420
 

Promise queue for AngularJS services

Promise queue for AngularJS services

AngularJSRecently I came across a problem using AngularJS where I had multiple controllers calling a service function that did an ajax request and returned a promise. The issue was that these multiple controllers would all call the same function and it would make N number of calls to the server to return the same data. I couldn’t let that stand…

In order to resolve this I introduced the concept of a promise queue. The first request to the function will create a deferred promise that is added to an array and toggles a isRunning flag before launching the ajax request. Future calls to this function, while it is in the isRunning state, will simply have their promise added to the array.

Once the ajax request returns the isRunning state will be removed and all the promises in the array will be resolved and purged from the array.

mymodule.service('WebService', function ($http, $q) {
    var processQueue = {
        isRunning: [],
        promises: []
    };
    return {
        LongRunningRequest: function (userId) {
            var methodName = 'LongRunningRequest';
            var defer = $q.defer();
            if (processQueue.isRunning.indexOf(methodName) == -1) {
                processQueue.isRunning.push(methodName);
                $http.get('<path to your web service>' + userId).success(function (data) {
                    _.each(
                        _.filter(processQueue.promises, function (value, index) {
                            return value.method == methodName;
                        }), function (value, index) {
                            processQueue.promises.splice(_.indexOf(processQueue, { id: value.id }));
                            value.promise.resolve(data);
                        });
                    processQueue.isRunning.splice(processQueue.isRunning.indexOf(methodName));
                });
            }
            processQueue.promises.push({
                method: methodName,
                promise: defer,
                id: Date.now()

            });
            return defer.promise;
        }
    };
});

Note on line 13 the use of the UnderscoreJS library to traverse and process the array.

Jonathan Sheely

Sr Software Engineer at InspectorIT. Jonathan is an out of the box thinker who has over 10 years experience building and supporting web application software and infrastructure. Jon specializes in ASP.NET C#, Javascript and CSS but is willing to learn anything that gets the job done.

2 Comments