Promise Pool Concurrency in JavaScript

Level 5413 keystrokes

Promise pool limits concurrent async operations to prevent resource exhaustion.

JavaScript code

// Function to run tasks with limited concurrency
1async function promisePool(tasks, concurrency) {
// Array to store results in order
2 const results = [];
// Shared index for task distribution
3 let index = 0;
4
// Worker function that processes tasks
5 async function worker() {
// Keep processing while tasks remain
6 while (index < tasks.length) {
// Claim the next index; safe because workers only interleave at await
7 const i = index++;
// Execute task and store result
8 results[i] = await tasks[i]();
9 }
10 }
11
// Start 'concurrency' workers in parallel and wait until all are done
12 await Promise.all(Array(concurrency).fill().map(worker));
// Return all results in order
13 return results;
14}
15
// Create 5 async tasks that double numbers
16const tasks = [1, 2, 3, 4, 5].map(n => () =>
17 new Promise(r => setTimeout(() => r(n * 2), 50))
18);
19
// Run with concurrency of 2, output: [2, 4, 6, 8, 10]
20promisePool(tasks, 2).then(console.log);

Output

[ 2, 4, 6, 8, 10 ]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 16
  • )× 16
  • =× 9
  • ;× 8
  • ,× 7
  • .× 7
  • [× 4
  • ]× 4
  • >× 4
  • {× 3

More JavaScript examples at level 5

← JavaScript typing practice