-
Notifications
You must be signed in to change notification settings - Fork 1
/
throttle.ts
39 lines (36 loc) · 1.05 KB
/
throttle.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
export type Fn<T> = () => Promise<T>;
/** 同時に一定数だけPromiseを走らせる函数
*
* 最後に追加したjobから実行する
*
* @param max 同時に動かすPromiseの最大数
* @return jobを動かして結果を返す函数
*/
export const makeThrottle = <T>(max: number): (job: Fn<T>) => Promise<T> => {
const queue: [
Fn<T>,
(value: T) => void,
(error: unknown) => void,
][] = [];
const pendings = new Set<Promise<unknown>>();
const runNext = (prev: Promise<unknown>) => {
pendings.delete(prev);
const task = queue.pop();
if (!task) return;
const promise: Promise<void> = task[0]()
.finally(() => runNext(promise))
.then((result) => task[1](result))
.catch((error) => task[2](error));
pendings.add(promise);
};
return (job) => {
if (pendings.size < max) {
const promise = job().finally(() => runNext(promise));
pendings.add(promise);
return promise;
}
return new Promise((resolve, reject) => {
queue.push([job, resolve, reject]);
});
};
};