UNPKG

@simplito/privmx-webendpoint

Version:

PrivMX Web Endpoint library

71 lines (70 loc) 1.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Queue = void 0; class Queue { items = []; func; processing = false; enqueue(item) { this.items.push(item); } dequeue() { return this.items.shift(); } peek() { return this.items[0]; } get size() { return this.items.length; } isEmpty() { return this.items.length === 0; } clear() { this.items.length = 0; } toArray() { return this.items.slice(); } assignProcessorFunc(func) { this.func = func; } async processAll() { if (this.processing) { return; } if (!this.func) { throw new Error("No task processor function assigned"); } this.processing = true; while (this.items.length > 0) { const item = this.items.shift(); if (!item) continue; const randId = Math.random(); try { await this.func(item); await this.awaiter(); } catch (err) { console.error("Error while processing queue item", randId, err); } } this.processing = false; } async awaiter() { return new Promise((resolve) => setTimeout(() => resolve(), 5000)); } [Symbol.iterator]() { let idx = 0; const arr = this.items; return { next() { if (idx < arr.length) return { value: arr[idx++], done: false }; return { value: undefined, done: true }; }, }; } } exports.Queue = Queue;