-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.4 An asynchronous map().ts
70 lines (60 loc) · 1.34 KB
/
5.4 An asynchronous map().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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { setTimeout } from 'timers/promises';
class Semaphore {
/**
* The number of available permits
*/
private permits: number;
/**
* @param concurrency - The number of concurrent operations that can be executed
*/
constructor(permits: number) {
this.permits = permits;
}
/**
* Acquires a permit, blocking until one is available
*/
public async acquire(): Promise<void> {
while (this.permits <= 0) {
await setTimeout(0);
}
this.permits--;
}
/**
* Releases a permit, allowing other blocked operations to proceed
*/
public release(): void {
this.permits++;
}
}
async function mapAsync<T, R>(
iterable: T[],
callback: (value: T) => R | Promise<R>,
concurrency: number
): Promise<R[]> {
const semaphore = new Semaphore(concurrency);
const results = Array<R>(iterable.length);
const promises = iterable.map(async (item, index) => {
await semaphore.acquire();
try {
results[index] = await callback(item);
} finally {
semaphore.release();
}
});
await Promise.all(promises);
return results;
}
const main = async () => {
console.time();
const results = await mapAsync(
[1, 2, 3, 4, 5],
async item => {
await setTimeout(item * 1000);
return item * 2;
},
5
);
console.timeEnd();
console.log(results);
};
main();