Promise Pool Concurrent Map Backpressure
Run async tasks through a fixed concurrency pool with backpressure collecting results in order while limiting outstanding promises.
Code
export async function promisePool(items,worker,concurrency=4){const results=new Array(items.length);let next=0;async function run(){while(true){const i=next++;if(i>=items.length)return;results[i]=await worker(items[i],i);}}const runners=Array.from({length:Math.min(concurrency,items.length)},()=>run());await Promise.all(runners);return results;}How it works
Promise Pool Concurrent Map Backpressure is built around the functions promisePool and run.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
- The guard
i>=items.lengthshort-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
Signature: export async function promisePool(items,worker,concurrency=4)
Callers only need promisePool — everything else stays internal.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `promisePool`, `run` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.