Promise queue for AngularJS 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.

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

Jonathan Sheely

Sr Software Engineer at Maxiom Technology. 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.