Add QueuedEventEmitter, use it for GuildSavedMessages events

This commit is contained in:
Dragory 2018-11-24 14:58:54 +02:00
parent 01d73565b6
commit effaff5dc8
3 changed files with 77 additions and 3 deletions

36
src/Queue.ts Normal file
View file

@ -0,0 +1,36 @@
type QueueFn = (...args: any[]) => Promise<any>;
export class Queue {
protected running: boolean = false;
protected queue: QueueFn[] = [];
protected timeout: number = 10 * 1000;
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());
}
}