@juit/pgproxy-pool 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/queue.ts ADDED
@@ -0,0 +1,47 @@
1
+ export type Task<T> = () => T | PromiseLike<T>
2
+
3
+ class Executor<T> {
4
+ constructor(
5
+ private _task: Task<T>,
6
+ private _resolve: (result: T) => void,
7
+ private _reject: (error: any) => void,
8
+ ) {}
9
+
10
+ execute(): Promise<void> {
11
+ return Promise.resolve().then(async () => {
12
+ try {
13
+ const result = await this._task()
14
+ this._resolve(result)
15
+ } catch (error) {
16
+ this._reject(error)
17
+ }
18
+ })
19
+ }
20
+ }
21
+
22
+ export class Queue {
23
+ private _queue: Executor<any>[] = []
24
+ private _running: boolean = false
25
+
26
+ private _run(): void {
27
+ if (this._running) return
28
+
29
+ const next = this._queue.splice(0, 1)[0]
30
+ if (! next) return
31
+
32
+ this._running = true
33
+
34
+ void next.execute().finally(() => {
35
+ this._running = false
36
+ this._run()
37
+ })
38
+ }
39
+
40
+ enqueue<T>(task: Task<T>): Promise<T> {
41
+ return new Promise<T>((resolve, reject) => {
42
+ const executor = new Executor(task, resolve, reject)
43
+ this._queue.push(executor)
44
+ process.nextTick(() => this._run())
45
+ })
46
+ }
47
+ }