]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/batch_promises.js
LP 2061136 follow-up: ng lint --fix
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / batch_promises.js
1 /**
2  * Module for batching promises
3  *
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.
7  * 
8  * Within each batch, calls are sent simultaneously. The batches
9  * themselves are run sequentially.
10  *
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
14  * wait times. 
15  *
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
18  * using orderBy.
19  * 
20  * You can just replace $q.all with egBatchPromises.all
21  */
22
23 angular.module('egBatchPromisesMod', [])
24
25 .factory('egBatchPromises', ['$q', function($q) {
26
27     var service = {};
28
29     // Helper method to break an array into chunks of a specified size
30     service.createChunks = function(array_to_be_chunked, chunk_size = 10) {
31         var results = [];
32     
33         while (array_to_be_chunked.length) {
34             results.push(array_to_be_chunked.splice(0, chunk_size));
35         }
36     
37         return results;
38     };
39
40     // Helper method that adds a batch of simultaneous promises to a sequential
41     // chain
42     service.addBatchToChain = function(chain, batch) {
43         return chain.then(() => $q.all(batch));
44     }
45
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());
50     };
51
52     return service;
53 }]);
54