-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPractice.js
More file actions
51 lines (47 loc) · 1.14 KB
/
Practice.js
File metadata and controls
51 lines (47 loc) · 1.14 KB
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
43
44
45
46
47
48
49
50
51
// Simulated async task
function fetchData(id) {
return new Promise((resolve) => {
const delay = Math.floor(Math.random() * 3000); // Random delay up to 3s
setTimeout(() => {
console.log(`Fetched data for ${id} after ${delay}ms`);
resolve(`result-${id}`);
}, delay);
});
}
const tasks = [
() => fetchData(1),
() => fetchData(2),
() => fetchData(3),
() => fetchData(4),
() => fetchData(5),
];
const limit = 2;
const runWithLimit = (tasks, limit) => {
let results = new Array(tasks.length);
let progress = 0;
let index = 0;
return new Promise((resolve, reject) => {
function executeTask() {
while (progress < limit && tasks.length > 0) {
const task = tasks[index];
task()
.then(() => {
results[]
})
.catch(reject)
.finally(() => {
progress--;
index++;
if (index === tasks.length) {
resolve(results);
}
executeTask();
});
}
}
executeTask();
});
};
runWithLimit(tasks, limit).then((results) => {
console.log("All results:", results);
});