promise queue for angular js services

Promise queue for AngularJS services


Recently 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…

What is Promise Queue for AngularJS Services?

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.

[code lang=”javascript”]
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) {
$http.get(‘<path to your web service>’ + userId).success(function (data) {
_.filter(processQueue.promises, function (value, index) {
return value.method == methodName;
}), function (value, index) {
processQueue.promises.splice(_.indexOf(processQueue, { id: }));
method: methodName,
promise: defer,

return defer.promise;

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