-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
52 lines (41 loc) · 1.23 KB
/
app.ts
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
52
class PromisePoll<T> {
private readonly queue: (() => Promise<T>)[]
constructor(){
this.queue = []
}
add(f: () => Promise<T>) {
this.queue.push(f)
}
async getResults(maxConcurrent: number) : Promise<T[]> {
const getResultsResponse = []
while(this.queue.length > 0){
const currentPromises: (Promise<T>)[] = [];
while(currentPromises.length < maxConcurrent){
const promiseShift: (() => Promise<T>) = this.queue.shift()
currentPromises.push(promiseShift())
}
const result = await Promise.all(currentPromises)
getResultsResponse.push(...result)
}
return getResultsResponse
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
console.log("Started.");
const runner = new PromisePoll<number>();
for (let i = 0 ; i < 100; ++i) {
runner.add(async () => {
console.log(`Printing ${i}`);
await sleep(1000);
return i;
});
}
const results = await runner.getResults(10);
console.log("Results:");
console.log(results);
console.log("Done.");
}
main();