Promise.all with a concurrency limit
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Like `Promise.all(items.map(fn))`, but with at most `limit` calls of the async function `fn(item)` running at the same time. Resolve with the results in the order of `items`. Start the next item as soon as any running one finishes. If a call rejects, reject. Tests run on a fake clock: `setTimeout`, `clearTimeout` and `Date.now` are simulated, so waits are instant and exact.
What this exercise teaches
Workers share a counter, so whichever finishes first claims the next item at once, and storing by index keeps the results in input order. Working in fixed batches instead would wait for the slowest item of every batch.
A hint if you get stuck
Start `limit` workers. Each worker loops: take the next unclaimed index, `await fn(items[i])`, store the result at `results[i]`, repeat until no items are left. Then `await Promise.all(workers)`.
This exercise is part of Pro
Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.
You create a free account first, so Pro is attached to it.
Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.