3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-05-17 23:25:02 +00:00

Add QueuedEventEmitter, use it for GuildSavedMessages events

This commit is contained in:
Dragory 2018-11-24 14:58:54 +02:00
parent b2a7887fef
commit 034391d9fe
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());
}
}