-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
32 lines (27 loc) · 888 Bytes
/
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
import splitArrayIntoBatches from './lib/splitArrayIntoBatches.js';
export { default as createStream } from './lib/createStream.js';
export const createPromise = (
tasks,
concurrency,
interval = 0,
failFast = true,
) => {
const processBatches = (batches, prevResults = []) => {
if (!batches.length) {
return Promise.resolve(prevResults);
}
return Promise.all(
batches[0].map(fn => (failFast ? fn() : fn().catch(err => err))),
).then((batchResults) => {
const results = [...prevResults, ...batchResults];
return (batches.length <= 1)
? results
: new Promise((resolve, reject) => setTimeout(
() => processBatches(batches.slice(1), results).then(resolve, reject),
interval,
));
});
};
return processBatches(splitArrayIntoBatches(tasks, concurrency));
};
export default createPromise;