Promise.all fires everything at once. That's fine for five requests and a disaster for five thousand: you hit rate limits, exhaust sockets, or get your IP throttled. What you usually want is "run these, but at most N at a time". Here's a tiny, dependency-free way to do it.
In a recent development, instead of a queue and callbacks, we start limit workers. Each worker is a loop that grabs the next index and awaits that task. When a task finishes, the worker immediately takes the next one, so there are always up to limit tasks in flight.
In a recent development, why is next++ safe without locks? JavaScript runs your code on a single thread. The read-and-increment happens synchronously between awaits, so two workers can never grab the same index.
Results are written by index, so the output order matches the input order, even if task 3 finishes before task 1.
In a recent development, note that we pass functions that return promises, not promises. A promise starts running the moment it's created, so urls.map((u) => fetch(u)) would fire everything immediately and defeat the limit.
I tested it with Node's built-in runner (node --test):.
What's your go-to pattern for this? Let me know in the comments.
