Created
September 26, 2019 22:34
-
-
Save TylerSustare/e4a2aabd6bcb6b0674d1d224dc806902 to your computer and use it in GitHub Desktop.
Sequential Promise.all() 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
const waait = i => new Promise(res => setTimeout(() => { return res(i); }, 2000)); | |
const batchedPromiseAll = async (array) => { | |
let requests = array.slice(0); | |
let results = []; | |
let processBatch = async (chunks, results) => { | |
let curr; | |
try { | |
curr = await Promise.all(chunks.map(prop => waait(prop))); | |
results.push(curr); | |
console.log(curr); | |
} catch (err) { | |
throw err | |
} | |
return curr !== undefined && requests.length | |
? processBatch(requests.splice(0, 5), results) | |
: results | |
} | |
const res = await processBatch(requests.splice(0, 5), results) | |
console.log(JSON.stringify(res, null, 2)); | |
} | |
const app = async () => { | |
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; | |
await batchedPromiseAll(array); | |
} | |
app(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment