Update types for Queue
This commit is contained in:
parent
772d13fd94
commit
b254022db2
1 changed files with 10 additions and 9 deletions
|
@ -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());
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue