4 ms·
Eh, it's so easy to provide your own implementation that does this, but I guess it wouldn't hurt to include in the standard-library since we already have someth
by capableweb 3y ago
Eh, it's so easy to provide your own implementation that does this, but I guess it wouldn't hurt to include in the standard-library since we already have something like Promise.all()
Here is the implementation I typically use for doing just that:
async function executeQueue(promises, concurrentLimit) {
let index = 0;
let activePromises = [];
async function manageQueue() {
if (index >= promises.length && activePromises.length === 0) return;
while (activePromises.length < concurrentLimit && index < promises.length) {
const promise = promises[index]();
activePromises.push(promise);
index++;
promise.then(() => {
activePromises = activePromises.filter(p => p !== promise);
manageQueue();
});
}
}
await manageQueue();
await Promise.all(activePromises);
}
Used like this:
function r(i, resolve) {
console.log(`Task ${i}`)
resolve(`Task ${resolve}`)
}
// Example usage
const promises = [
() => new Promise(resolve => setTimeout(() => r("Task 1", resolve), 2000)),
() => new Promise(resolve => setTimeout(() => r("Task 2", resolve), 1000)),
() => new Promise(resolve => setTimeout(() => r("Task 3", resolve), 3000)),
() => new Promise(resolve => setTimeout(() => r("Task 4", resolve), 500)),
() => new Promise(resolve => setTimeout(() => r("Task 5", resolve), 1500))
];
executeQueue(promises, 4).then(() => {
console.log("All tasks completed!");
});
Would print:
"Task Task 4"
"Task Task 2"
"Task Task 1"
"Task Task 5"
"Task Task 3"
"All tasks completed!"