javascript
26 lines · 7 steps
Bounded-concurrency async map in JavaScript
Run a worker over many items with a fixed number of tasks in flight, preserving result order.
Explained by
highlit
1async function mapWithConcurrency(items, limit, worker) {
2 const results = new Array(items.length);
3 let nextIndex = 0;
4
5 async function runner() {
6 while (true) {
7 const current = nextIndex++;
8 if (current >= items.length) return;
9 results[current] = await worker(items[current], current);
10 }
11 }
12
13 const pool = Array.from({ length: Math.min(limit, items.length) }, runner);
14 await Promise.all(pool);
15 return results;
16}
17
18async function mapSettledWithConcurrency(items, limit, worker) {
19 return mapWithConcurrency(items, limit, async (item, index) => {
20 try {
21 return { status: 'fulfilled', value: await worker(item, index) };
22 } catch (reason) {
23 return { status: 'rejected', reason };
24 }
25 });
26}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A shared mutable index lets a fixed set of workers pull tasks without overlapping.
- 2Writing results by original index keeps output order independent of completion order.
- 3Wrapping each worker in try/catch turns a fail-fast map into an allSettled-style one.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/bounded-concurrency-async-map-in-javascript-explained-javascript-4e10/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.