import type { MaybePromise } from "./utility-types"; import type { ResolvablePromise } from "./utils"; import { promiseTry, resolvablePromise } from "./utils"; type Job = (...args: TArgs) => MaybePromise; type QueueJob = { jobFactory: Job; promise: ResolvablePromise; args: TArgs; }; export class Queue { private jobs: QueueJob[] = []; private running = false; private tick() { if (this.running) { return; } const job = this.jobs.shift(); if (job) { this.running = true; job.promise.resolve( promiseTry(job.jobFactory, ...job.args).finally(() => { this.running = false; this.tick(); }), ); } else { this.running = false; } } push( jobFactory: Job, ...args: TArgs ): Promise { const promise = resolvablePromise(); this.jobs.push({ jobFactory, promise, args }); this.tick(); return promise; } }