
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) {
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;
}
};
});
[/code]
Note on line 13 the use of the UnderscoreJS
library to traverse and process the array.