UNPKG

tiny-async-pool

Version:

Run multiple promise-returning & async functions with limited concurrency using native ES9

26 lines (24 loc) 763 B
async function* asyncPool(concurrency, iterable, iteratorFn) { const executing = new Set(); async function consume() { const [promise, value] = await Promise.race(executing); executing.delete(promise); return value; } for (const item of iterable) { // Wrap iteratorFn() in an async fn to ensure we get a promise. // Then expose such promise, so it's possible to later reference and // remove it from the executing pool. const promise = (async () => await iteratorFn(item, iterable))().then( value => [promise, value] ); executing.add(promise); if (executing.size >= concurrency) { yield await consume(); } } while (executing.size) { yield await consume(); } } module.exports = asyncPool;