2018-11-24 14:58:54 +02:00
|
|
|
type QueueFn = (...args: any[]) => Promise<any>;
|
|
|
|
|
2019-02-23 21:19:46 +02:00
|
|
|
const DEFAULT_TIMEOUT = 10 * 1000;
|
|
|
|
|
2018-11-24 14:58:54 +02:00
|
|
|
export class Queue {
|
|
|
|
protected running: boolean = false;
|
|
|
|
protected queue: QueueFn[] = [];
|
2019-02-23 21:19:46 +02:00
|
|
|
protected timeout: number;
|
|
|
|
|
|
|
|
constructor(timeout = DEFAULT_TIMEOUT) {
|
|
|
|
this.timeout = timeout;
|
|
|
|
}
|
2018-11-24 14:58:54 +02:00
|
|
|
|
|
|
|
public add(fn) {
|
|
|
|
const promise = new Promise(resolve => {
|
|
|
|
this.queue.push(async () => {
|
|
|
|
await fn();
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!this.running) this.next();
|
|
|
|
});
|
|
|
|
|
|
|
|
return promise;
|
|
|
|
}
|
|
|
|
|
|
|
|
public next() {
|
|
|
|
this.running = true;
|
|
|
|
|
|
|
|
if (this.queue.length === 0) {
|
|
|
|
this.running = false;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const fn = this.queue.shift();
|
|
|
|
new Promise(resolve => {
|
|
|
|
// Either fn() completes or the timeout is reached
|
|
|
|
fn().then(resolve);
|
|
|
|
setTimeout(resolve, this.timeout);
|
|
|
|
}).then(() => this.next());
|
|
|
|
}
|
|
|
|
}
|