-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlimitConcurrency.js
42 lines (35 loc) · 1.06 KB
/
limitConcurrency.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function limitConcurrency(promises, maxConcurrency) {
return new Promise((resolve, reject) => {
const runningPromises = [];
let currentIndex = 0;
const executeNext = async () => {
if (currentIndex < promises.length) {
const promise = promises[currentIndex]();
currentIndex++;
runningPromises.push(promise);
promise.then(() => {
runningPromises.splice(runningPromises.indexOf(promise), 1);
if (runningPromises.length === 0) resolve();
}).finally(executeNext);
if (runningPromises.length < maxConcurrency) {
executeNext();
}
}
};
executeNext()
});
}
const promisesToExecute = [...Array(10)].map((item, index) => {
return () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Executed");
resolve();
}, 1000);
});
};
});
const maxConcurrency = 2; // Set our desired maximum concurrency
limitConcurrency(promisesToExecute, maxConcurrency).then(() => {
console.log('All promisеs complеtеd.');
});