File size: 686 Bytes
21dd449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Execute queue of promises in a streaming fashion.
 *
 * Optimized for streaming:
 * - Expects an iterable as input
 * - Does not return a list of all results
 *
 * Inspired by github.com/rxaviers/async-pool
 */
export async function promisesQueueStreaming<T>(
	factories: AsyncIterable<() => Promise<T>> | Iterable<() => Promise<T>>,
	concurrency: number
): Promise<void> {
	const executing: Promise<void>[] = [];
	for await (const factory of factories) {
		const e = factory().then(() => {
			executing.splice(executing.indexOf(e), 1);
		});
		executing.push(e);
		if (executing.length >= concurrency) {
			await Promise.race(executing);
		}
	}
	await Promise.all(executing);
}