Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
'use strict';

const requestToExternalService = function(d) {
  // Replace with a promise that does real work here...
  return new Promise(resolve => {
    console.log(d);

    // Delay demonstrates we are indeed batching
    setTimeout(resolve, 250);
  });
};

const chunk = (array, batchSize = 5) => {
  const chunked = [];
  for(let i = 0; i < array.length; i += batchSize) {
    chunked.push(array.slice(i, i + batchSize))
  }

  return chunked;
}

// Replace with real data
const chunkedData = chunk([...Array(21).keys()]);
console.log(chunkedData);
/*
 * [ [ 0, 1, 2, 3, 4 ],
 *   [ 5, 6, 7, 8, 9 ],
 *   [ 10, 11, 12, 13, 14 ],
 *   [ 15, 16, 17, 18, 19 ],
 *   [ 20 ] ]
*/

const reducer = (chain, batch) => chain
  .then(() => Promise.all(
    batch.map(d => requestToExternalService(d))
  ));

const promiseChain = chunkedData.reduce(
  reducer,
  Promise.resolve()
);
promiseChain.then(() => console.log('done'));
node v9.7.1 linux/amd64