genki.nakamura
Build a Concurrent Task Scheduler
Implement a JavaScript function called runWithConcurrency() that executes asynchronous tasks while limiting the maximum number of tasks running simultaneously.
Requirements:
-
Accept an array of asynchronous task functions.
-
Accept a maximum concurrency limit.
-
Never execute more than the specified number of tasks simultaneously.
-
Execute all tasks, even if some tasks fail.
-
Preserve the original task order in the returned results.
-
Return both successful results and errors.
-
Handle an empty task array.
Additional challenges
- What happens if the concurrency limit is 0?
- How would you handle a task that never resolves?
- How would you implement cancellation using
AbortController? - How would you prevent memory leaks when processing 100,000 tasks?
First Post!
MarcusHale
Fun one. The version I’d write starts min(limit, tasks.length) workers that each grab the next index from a shared counter, await that task, and write { status, value } or { status, reason } into results[i]. Writing by index keeps the original order for free, and since every worker catches its own errors, one failure never stops the rest. That also covers the 100,000 case. You never build 100k promises up front, only as many as the limit. For a limit of 0 I’d just throw a RangeError. Otherwise you get zero workers and it resolves right away without running anything, which is a nasty surprise. The never-resolving task is the tricky bit. Racing it against a timeout frees the slot, but the task itself keeps running because a promise can’t be cancelled. That’s where AbortController earns its place: pass a signal into each task and abort it on timeout, so tasks that respect the signal actually stop.
Popular Backend topics
What is the difference between using `:references` and `:belongs_to` in a generate command in Rails?
Other popular topics
Latest in JavaScript
Backend>Questions
Categories:
Sub Categories:
Popular Portals
- /elixir
- /rust
- /wasm
- /ruby
- /erlang
- /phoenix
- /keyboards
- /python
- /js
- /rails
- /security
- /go
- /swift
- /vim
- /java
- /clojure
- /typescript
- /emacs
- /haskell
- /svelte
- /onivim
- /kotlin
- /react
- /c-plus-plus
- /crystal
- /tailwind
- /gleam
- /ocaml
- /elm
- /vscode
- /flutter
- /html
- /ash
- /deepseek
- /zig
- /opensuse
- /php
- /centos
- /react-native
- /scala
- /lisp
- /sublime-text
- /textmate
- /nixos
- /debian
- /agda
- /deno
- /django
- /kubuntu
- /nodejs
- /arch-linux
- /ubuntu
- /spring
- /revery
- /manjaro
- /julia
- /quarkus
- /lua
- /diversity
- /laravel









