Repository navigation
Expand file tree
/
Copy pathpromisebuffer.ts
More file actions
83 lines (76 loc) · 2.31 KB
/
Copy pathpromisebuffer.ts
File metadata and controls
83 lines (76 loc) · 2.31 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
import { SentryError } from './error';
import { SyncPromise } from './syncpromise';
/** A simple queue that holds promises. */
export class PromiseBuffer<T> {
/** Internal set of queued Promises */
private readonly _buffer: Array<PromiseLike<T>> = [];
public constructor(protected _limit?: number) {}
/**
* Says if the buffer is ready to take more requests
*/
public isReady(): boolean {
return this._limit === undefined || this.length() < this._limit;
}
/**
* Add a promise to the queue.
*
* @param task Can be any PromiseLike<T>
* @returns The original promise.
*/
public add(task: PromiseLike<T>): PromiseLike<T> {
if (!this.isReady()) {
return SyncPromise.reject(new SentryError('Not adding Promise due to buffer limit reached.'));
}
if (this._buffer.indexOf(task) === -1) {
this._buffer.push(task);
}
task
.then(() => this.remove(task))
.then(null, () =>
this.remove(task).then(null, () => {
// We have to add this catch here otherwise we have an unhandledPromiseRejection
// because it's a new Promise chain.
}),
);
return task;
}
/**
* Remove a promise to the queue.
*
* @param task Can be any PromiseLike<T>
* @returns Removed promise.
*/
public remove(task: PromiseLike<T>): PromiseLike<T> {
const removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0];
return removedTask;
}
/**
* This function returns the number of unresolved promises in the queue.
*/
public length(): number {
return this._buffer.length;
}
/**
* This will drain the whole queue, returns true if queue is empty or drained.
* If timeout is provided and the queue takes longer to drain, the promise still resolves but with false.
*
* @param timeout Number in ms to wait until it resolves with false.
*/
public drain(timeout?: number): PromiseLike<boolean> {
return new SyncPromise<boolean>(resolve => {
const capturedSetTimeout = setTimeout(() => {
if (timeout && timeout > 0) {
resolve(false);
}
}, timeout);
SyncPromise.all(this._buffer)
.then(() => {
clearTimeout(capturedSetTimeout);
resolve(true);
})
.then(null, () => {
resolve(true);
});
});
}
}