export class SerialMessageQueue { private tail: Promise = Promise.resolve(); private pending = 0; get pendingCount(): number { return this.pending; } enqueue(task: () => Promise): Promise { this.pending += 1; const execution = this.tail.then(task); this.tail = execution .then( () => undefined, () => undefined, ) .finally(() => { this.pending -= 1; }); return execution; } async waitForIdle(): Promise { await this.tail; } }