Menu

1 / 2

Run async tasks with a concurrency limit in plain JavaScript (with a test you can run)

DEV Community: node·Yehia Mahmoud·2 days ago
#Pkd9vxcx
#devtonodejs#devto#dev#peak#const
Long article (590 words) — no AI summary yet.
Reading 0:00
15s threshold

Promise.all on a big list starts every task at once. If each task is an HTTP call, you can hit rate limits or open too many sockets. A small worker pool fixes that in about 12 lines, with no library.

The code

async function mapLimit ( items , limit , fn ) { const results = new Array ( items . length ) ; let next = 0 ; async function worker ( ) { while ( next < items . length ) { const i = next ++ ; results [ i ] = await fn ( items [ i ] , i ) ; } } const workers = Array . from ( { length : Math . min ( limit , items . length ) } , worker ) ; await Promise . all ( workers ) ; return results ; }

Enter fullscreen mode

Exit fullscreen mode

How it works

limit workers start together.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.