Hello! Welcome to your next lesson on advanced asynchronous patterns.
In our last session, we mastered how to create cancellable asynchronous operations using AbortController and AbortSignal. This gave us fine-grained control over the lifecycle of a single long-running task. But what happens when you need to run not one, but hundreds or thousands of asynchronous tasks, like fetching data from a list of URLs or processing a batch of files?
Running them all at once with Promise.all can quickly lead to problems:
- Resource Exhaustion: You might overwhelm your own network connection or run out of memory.
- API Rate Limiting: Most external services will block or throttle you if you send too many requests simultaneously.
- Browser Limits: Browsers limit the number of concurrent connections to a single domain.
Today, we'll solve this classic problem. The learning outcome for this lesson is to implement a promise pool to control concurrency when processing multiple async tasks. This powerful pattern allows you to execute a large number of promises while ensuring only a specified number run in parallel at any given time, maximizing throughput without overloading resources.
1. The Problem with Simple Batching
Your first instinct might be to break the tasks into fixed-size chunks and run each chunk with Promise.all. You might write code that looks like this:
const tasks = [/* ... 100 async functions ... */];
const CONCURRENCY_LIMIT = 5;
for (let i = 0; i < tasks.length; i += CONCURRENCY_LIMIT) {
const batch = tasks.slice(i, i + CONCURRENCY_LIMIT);
await Promise.all(batch.map(task => task()));
}
This seems logical, but it has a significant performance flaw. To understand why, let's turn to a clear explanation.
NodeJS/JavaScript: execute at most N tasks at the same time
The article 'NodeJS/JavaScript: execute at most N tasks at the same time' by Antoine Vastel clearly explains the inefficiency of this batching approach.
Read the section titled 'Precision regarding the problem to solve'. Focus on the example code and the author's explanation of why using Promise.all in a loop is suboptimal.
As the article points out, the core issue is that Promise.all waits for every promise in the batch to complete before the loop can proceed to the next batch. If one task in a batch of 5 takes 10 seconds and the other four take only 1 second, your pool will be running at 20% capacity (1 out of 5 "slots" busy) for 9 seconds. This is inefficient.
A true promise pool should immediately start a new task as soon as any other task finishes, ensuring the number of concurrent operations stays at the maximum limit for as long as there are tasks waiting.
2. The Core Concept: A Self-Sustaining Chain
So, how do we build a system that immediately pulls in new work? The most elegant solution doesn't involve complex timers or counters. Instead, it relies on creating a "self-sustaining chain reaction."
Imagine a conveyor belt with a limited number of processing stations (our concurrency limit). The key idea is to make each task responsible for triggering the next available task as soon as it finishes its own work.
2636. Promise Pool - In-Depth Explanation
The 'Intuition' section of the 'Promise Pool' explanation on Algo.monster provides a fantastic mental model for this concept.
Read the 'Intuition' section. Focus on the core challenge and the key insight about a 'self-sustaining chain reaction.' The idea of wrapping each function so it 'carries the responsibility of starting the next one' is the central theme of our implementation.
This "pass the baton" approach is the heart of an efficient promise pool. When a task completes, it reaches into a queue of waiting tasks, pulls one out, and starts it. This ensures our processing stations are always busy.
3. Implementation: The Wrapper and Queue Pattern
Let's translate this concept into code. We will implement a promisePool function that takes an array of asynchronous functions (our tasks) and a concurrency limit n.
The implementation involves three main steps:
- Wrap each task: Create a new async function (a "wrapper") for each original task. This wrapper will first execute the original task and then, upon completion, pull the next waiting task from a queue and execute it.
- Partition the tasks: Split the wrapped tasks into two groups: an initial
runninggroup (of sizen) and awaitingQueuefor all the rest. - Start the chains: Execute the initial
runninggroup usingPromise.all. Because of our wrappers, these initial chains will automatically consume the entirewaitingQueue. The finalPromise.allwill only resolve when all the chains have completed, meaning all tasks are done.
2636. Promise Pool - In-Depth Explanation
Let's study a concise and effective implementation of this pattern from Algo.monster.
First, carefully review the JavaScript code in the 'Solution Implementation' section. Then, read the 'Solution Approach' and 'Example Walkthrough' sections. The walkthrough provides a concrete timeline that is invaluable for understanding how the concurrency is managed dynamically.
Let's consolidate that logic into our own promisePool function.
/**
* Type definition for a function that returns a Promise.
* @typedef {() => Promise<any>} AsyncTask
*/
/**
* Executes an array of async functions with a concurrency limit.
* @param {AsyncTask[]} functions - Array of async functions to execute.
* @param {number} n - The concurrency limit.
* @returns {Promise<any>} A promise that resolves when all tasks are complete.
*/
function promisePool(functions, n) {
// If there are no functions, we're done.
if (!functions || functions.length === 0) {
return Promise.resolve();
}
return new Promise((resolve) => {
let inProgress = 0;
let taskIndex = 0;
let done = 0;
const totalTasks = functions.length;
function runNext() {
// If all tasks are done, resolve the main promise.
if (done === totalTasks) {
resolve();
return;
}
// While there are tasks to run AND we are under the concurrency limit
while (taskIndex < totalTasks && inProgress < n) {
const currentTask = functions[taskIndex];
taskIndex++;
inProgress++;
currentTask().finally(() => {
inProgress--;
done++;
// A slot has opened up, try to run the next task.
runNext();
});
}
}
// Kick off the initial set of tasks.
runNext();
});
}
The implementation you studied in the reading uses a slightly different but equally valid technique with pre-wrapped functions and a queue. The version above uses a "worker" model where a runNext function acts as a dispatcher. Both achieve the same goal: as soon as a task finishes (.finally()), a new one is started, keeping the number of inProgress tasks at or below n.
Test your understanding!
In the promisePool function above, why is the runNext() function called both at the end of the script and inside the .finally() block? What would happen if you removed the call from the .finally() block?
Show answer
The initial call to runNext() at the end is what "primes the pump"—it starts the first n tasks.
The call inside .finally() is the critical part that ensures the pool continues to work. When a task completes, inProgress decrements, opening up a "slot". Calling runNext() again checks if there are more tasks waiting (taskIndex < totalTasks) and if there's a free slot (inProgress < n). If so, it starts a new task.
If you removed runNext() from the .finally() block, only the first n tasks would ever run. Once they completed, no new tasks would ever be started, and the pool would sit idle while the rest of the tasks remained unexecuted.
4. Performance and Robustness
Given your background in computer science, it's worth analyzing the efficiency and potential failure points of this pattern.
2636. Promise Pool - In-Depth Explanation
The Algo.monster article also provides a good analysis of complexity and common issues.
Read the sections 'Time and Space Complexity' and 'Common Pitfalls'. Pay special attention to the reasoning for O(m) complexity and the point about exception handling.
Complexity Analysis:
- Time Complexity: , where is the total number of functions. Although we limit concurrency, every single task must be executed. The total time will be dominated by the sum of the execution times of all tasks, distributed across
nworkers. - Space Complexity: . We need to store the entire array of
mfunctions. The implementation using pre-wrapped functions also creates a new array ofmwrappers.
Exception Handling:
A key consideration for a robust pool is how it handles errors. Our simple implementation uses .finally(), which ensures runNext() is called whether the task succeeded or failed. This is good—it prevents the pool from stalling if one task throws an error. However, the Promise.all() at the top level will still reject if any single promise rejects, and you won't get the results from the successful tasks. For more advanced use cases, you might use Promise.allSettled() to gather all outcomes, or build a more complex pool that tracks successes and failures separately, like the class-based example in the first article we looked at.
5. Putting it to Use
Let's apply our promisePool function to a practical problem.
Test your skills!
You are given an array of 100 user IDs. You need to fetch the profile for each user from an API endpoint https://api.example.com/users/{id}. The fetchUserProfile function below simulates this async operation.
Using the promisePool function we built, write a script to fetch all 100 profiles with a concurrency limit of 10. Log a message when all profiles have been fetched.
// This function simulates fetching a user profile.
// It resolves with the user ID after a random delay.
function fetchUserProfile(userId) {
return new Promise(resolve => {
const delay = Math.random() * 1000 + 200; // random delay between 200ms and 1200ms
setTimeout(() => {
console.log(`Fetched profile for user ${userId}`);
resolve({ userId, profileData: `...data for ${userId}` });
}, delay);
});
}
const userIds = Array.from({ length: 100 }, (_, i) => i + 1);
// Your code goes here...
Show answer
Here is one way to solve it:
// This function simulates fetching a user profile.
// It resolves with the user ID after a random delay.
function fetchUserProfile(userId) {
return new Promise(resolve => {
const delay = Math.random() * 1000 + 200; // random delay between 200ms and 1200ms
setTimeout(() => {
console.log(`Fetched profile for user ${userId}`);
resolve({ userId, profileData: `...data for ${userId}` });
}, delay);
});
}
const userIds = Array.from({ length: 100 }, (_, i) => i + 1);
// 1. Create an array of async task functions.
// Each function, when called, will start one fetch operation.
const tasks = userIds.map(id => {
return () => fetchUserProfile(id);
});
// 2. Define the concurrency limit.
const concurrencyLimit = 10;
console.log('Starting to fetch user profiles with a promise pool...');
// 3. Run the tasks through the promise pool.
promisePool(tasks, concurrencyLimit)
.then(() => {
console.log('All user profiles have been fetched successfully!');
})
.catch(error => {
console.error('An error occurred in the promise pool:', error);
});
The key step is mapping the userIds to an array of functions (() => fetchUserProfile(id)). The promise pool expects an array of functions to call, not an array of promises that have already started.
Conclusion
You have now learned a critical pattern for managing large-scale asynchronous operations in JavaScript. This technique is fundamental in many real-world applications, from web scrapers and data migration scripts to front-end applications that need to load many resources efficiently.
Key Takeaways:
- Naive batching with
Promise.allin a loop is inefficient because it waits for the slowest task in a batch, leading to underutilized concurrency. - A true promise pool aims to keep the number of concurrent tasks at a constant maximum by starting a new task as soon as one finishes.
- This can be elegantly implemented using a "self-sustaining chain" pattern, where each completing task is responsible for triggering the next one from a waiting queue.
- The implementation requires careful management of state (which tasks are running, which are waiting) but provides significant performance gains.
- Robust promise pools must also consider error handling to prevent the entire pool from failing due to a single rejected promise.
Next Up
We have now explored how to cancel a single async task and how to manage the concurrent execution of many tasks. But what if the order of execution matters? In our next lesson, we will tackle the opposite problem: how to create an async queue to manage the sequential execution of asynchronous tasks, ensuring that one task begins only after the previous one has fully completed.