Update types for Queue

This commit is contained in:
Dragory 2021-05-22 13:34:25 +03:00
parent 772d13fd94
commit b254022db2
No known key found for this signature in database
GPG key ID: 5F387BA66DF8AAC1

View file

@ -1,23 +1,24 @@
import { SECONDS } from "./utils";
type QueueFn = (...args: any[]) => Promise<any>;
type InternalQueueFn = () => Promise<void>;
type AnyFn = (...args: any[]) => any;
const DEFAULT_TIMEOUT = 10 * SECONDS;
export class Queue {
protected running: boolean = false;
protected queue: QueueFn[] = [];
export class Queue<TQueueFunction extends AnyFn = AnyFn> {
protected running = false;
protected queue: InternalQueueFn[] = [];
protected timeout: number;
constructor(timeout = DEFAULT_TIMEOUT) {
this.timeout = timeout;
}
public add(fn) {
const promise = new Promise(resolve => {
public add(fn: TQueueFunction): Promise<void> {
const promise = new Promise<void>(resolve => {
this.queue.push(async () => {
await fn();
resolve(undefined);
resolve();
});
if (!this.running) this.next();
@ -26,7 +27,7 @@ export class Queue {
return promise;
}
public next() {
public next(): void {
this.running = true;
if (this.queue.length === 0) {
@ -37,7 +38,7 @@ export class Queue {
const fn = this.queue.shift()!;
new Promise(resolve => {
// Either fn() completes or the timeout is reached
fn().then(resolve);
void fn().then(resolve);
setTimeout(resolve, this.timeout);
}).then(() => this.next());
}