Run Async Tasks with a Concurrency Limit
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write runWithLimit(tasks, limit), where tasks is an array of functions that take no arguments and return a promise, and limit is a whole number of at least 1 (it may be larger than the number of tasks). Start tasks in array order, never with more than limit running at once, and start the next one as soon as a running one finishes. Return a promise of an array of the results in the order of tasks, not the order they finished in. If a task's promise rejects, reject with its reason straight away and start no more tasks; ones already running may carry on. An empty array resolves to an empty array.
Your code must pass
- Resolves with every result, in task order
- Starts limit tasks, then the next as soon as one finishes
- Never runs more than limit tasks at once
- Stops starting tasks after a rejection
- Resolves an empty array to an empty array