zappyzep/backend/src/Queue.ts

49 lines
980 B
TypeScript
Raw Normal View History

2019-08-18 16:40:15 +03:00
import { SECONDS } from "./utils";
type QueueFn = (...args: any[]) => Promise<any>;
2019-08-18 16:40:15 +03:00
const DEFAULT_TIMEOUT = 10 * SECONDS;
2019-02-23 21:19:46 +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;
}
public add(fn) {
const promise = new Promise(resolve => {
this.queue.push(async () => {
await fn();
2020-12-13 22:11:16 +02:00
resolve(undefined);
});
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());
}
2020-07-27 20:42:10 +03:00
public clear() {
this.queue.splice(0, this.queue.length);
}
}