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 concurrency1async function promisePool(tasks, concurrency) { // Array to store results in order2 const results = []; // Shared index for task distribution3 let index = 0;4 // Worker function that processes tasks5 async function worker() { // Keep processing while tasks remain6 while (index < tasks.length) { // Claim the next index; safe because workers only interleave at await7 const i = index++; // Execute task and store result8 results[i] = await tasks[i]();9 }10 }11 // Start 'concurrency' workers in parallel and wait until all are done12 await Promise.all(Array(concurrency).fill().map(worker)); // Return all results in order13 return results;14}15 // Create 5 async tasks that double numbers16const 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. 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