-
Notifications
You must be signed in to change notification settings - Fork 1
/
batch-request.js
43 lines (39 loc) · 1.27 KB
/
batch-request.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
43
/**
* Batch async requests, throttled with a delay
* to avoid hammering the network
*
* @param {Array} records
* @param {Function} request (returns Promise)
* @param {Object} options
* @returns {Object} result { error, data }
*/
const batchRequest = (records, request = () => {}, options = { batchSize: 100, delay: 100 }) => {
return new Promise(async resolve => {
let response = []
let data = []
let error = []
for (let i = 0; i < records.length; i += options.batchSize) {
const batch = records.slice(i, i + options.batchSize)
// capture individual errors
// as per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all#Promise.all_fail-fast_behaviour
const result = await Promise.all(
batch.map(record => request(record).catch(e => ({ record, error: new Error(e) })))
)
response = response.concat(result)
await delay(options.delay)
}
// separate successful requests from errors
response.forEach(res => {
res && (res.error instanceof Error) ? error.push(res) : data.push(res)
})
resolve({
error,
data
})
})
}
const delay = (ms = 150) => new Promise(resolve => setTimeout(resolve, ms))
module.exports = {
batchRequest,
delay
}