Last active
November 30, 2019 08:59
-
-
Save maapteh/19b1926fd307c2376044c12c77398b91 to your computer and use it in GitHub Desktop.
retrieve urls in batches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a mock request function | |
const sendRequest = (url) => { | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
resolve(`request resolved ${url}`) | |
}, 2000) | |
}) | |
} | |
// Helper: split array in batches | |
const splitInBatch = (arr, batchSize) => { | |
return arr.reduce((accumulator, element, index) => { | |
const batchIndex = Math.floor(index / batchSize); | |
if (Array.isArray(accumulator[batchIndex])) { | |
accumulator[batchIndex].push(element); | |
} else { | |
accumulator.push([element]); | |
} | |
return accumulator; | |
}, []); | |
} | |
// App | |
const batchSize = 3; | |
const urls = [1, 2, 3, 4, 5, 6, 7]; | |
const batches = splitInBatch(urls, batchSize); | |
const asyncForEach = async (array, callback) => { | |
for (let index = 0; index < array.length; index++) { | |
await callback(array[index], index, array); | |
} | |
} | |
;(async function() { | |
asyncForEach(batches, async (batch) => { | |
console.log('--- sending batch ---') | |
await Promise.all(batch.map(async(url) => { | |
const response = await sendRequest(url); | |
console.log(`✔ response`) | |
return response; | |
})) | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.npmjs.com/package/wait-on