Skip to content

Instantly share code, notes, and snippets.

@maapteh
Last active November 30, 2019 08:59
Show Gist options
  • Save maapteh/19b1926fd307c2376044c12c77398b91 to your computer and use it in GitHub Desktop.
Save maapteh/19b1926fd307c2376044c12c77398b91 to your computer and use it in GitHub Desktop.
retrieve urls in batches
// 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;
}))
});
})();
@maapteh
Copy link
Author

maapteh commented Nov 30, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment