Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sequential Promise.all() in batches
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