2 * Module for batching promises
4 * This service helps to reduce server load for repetitive OpenSRF
5 * calls by dividing a large array of promises into batches. It
6 * maintains the original order of the array when returning results.
8 * Within each batch, calls are sent simultaneously. The batches
9 * themselves are run sequentially.
11 * This represents a middle ground between running a ton of OpenSRF
12 * calls sequentially -- which leads to a long wait for the user --
13 * and running them simultaneously, which can result in some serious
16 * One use case is when you need to get several rows from pcrud,
17 * but the order of results is important and can't be just passed
20 * You can just replace $q.all with egBatchPromises.all
23 angular.module('egBatchPromisesMod', [])
25 .factory('egBatchPromises', ['$q', function($q) {
29 // Helper method to break an array into chunks of a specified size
30 service.createChunks = function(array_to_be_chunked, chunk_size = 10) {
33 while (array_to_be_chunked.length) {
34 results.push(array_to_be_chunked.splice(0, chunk_size));
40 // Helper method that adds a batch of simultaneous promises to a sequential
42 service.addBatchToChain = function(chain, batch) {
43 return chain.then(() => $q.all(batch));
46 // Returns a chain of chunked promises
47 service.all = function(array_of_promises, chunk_size = 10) {
48 var chunked_array = this.createChunks(array_of_promises, chunk_size);
49 return chunked_array.reduce(this.addBatchToChain, $q.when());