UNPKG

@intuitionrobotics/ts-common

Version:
69 lines 2.12 kB
import { addItemToArray, removeItemFromArray, } from "../index.js"; import { Logger } from "../core/logger/Logger.js"; export class Queue extends Logger { parallelCount = 1; running = 0; queue = []; onQueueEmpty; finalResolve; constructor(name) { super(name); } setParallelCount(parallelCount) { this.parallelCount = parallelCount; return this; } setOnQueueEmpty(onQueueEmpty) { this.onQueueEmpty = onQueueEmpty; return this; } addItem(toExecute, onCompleted, onError) { this.addItemImpl(toExecute.bind(this), onCompleted?.bind(this), onError?.bind(this)); this.execute(); } addItemImpl(toExecute, onCompleted, onError) { addItemToArray(this.queue, async (resolve) => { this.running++; try { const output = await toExecute(); onCompleted?.(output); } catch (e) { try { onError?.(e); } catch (e1) { this.logError("Error while calling onError"); this.logError("--- Original: ", e); this.logError("-- Secondary: ", e1); } } this.running--; resolve(); this.execute(); }); } ignore = () => { }; execute() { if (this.queue.length === 0 && this.running === 0) { if (this.onQueueEmpty) this.onQueueEmpty(); return this.finalResolve?.(); } for (let i = 0; this.running < this.parallelCount && i < this.queue.length; i++) { const toExecute = this.queue[0]; removeItemFromArray(this.queue, toExecute); new Promise(toExecute.bind(this)) .then(this.ignore) .catch(this.ignore); } } async executeSync() { await new Promise(resolve => { this.finalResolve = resolve; this.execute(); }); } } //# sourceMappingURL=queue.js.map