@beenotung/tslib
Version:
utils library in Typescript
98 lines (97 loc) • 2.67 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NonVoidResultPool = exports.VoidResultPool = void 0;
const array_1 = require("./array");
const result_1 = require("./result");
const ring_buffer_1 = require("./ring-buffer");
class VoidResultPool {
poolSize;
fs = new ring_buffer_1.RingBuffer((0, array_1.getMaxArraySize)());
running = 0;
constructor(poolSize) {
this.poolSize = poolSize;
}
run(f) {
this.fs.push(f);
this.next();
}
next() {
if (this.fs.length > 0 && this.running < this.poolSize) {
const f = this.fs.dequeue();
this.running++;
let x;
try {
x = f();
}
catch (e) {
// x = then(e, e => Promise.reject(e));
x = Promise.reject(e);
this.running--;
this.next();
}
(0, result_1.then)(x, () => {
this.running--;
this.next();
});
}
}
}
exports.VoidResultPool = VoidResultPool;
class NonVoidResultPool {
poolSize;
logError;
fs = new ring_buffer_1.RingBuffer((0, array_1.getMaxArraySize)());
running = 0;
constructor(poolSize, logError = true) {
this.poolSize = poolSize;
this.logError = logError;
}
/**
* @description error will be ignored
* */
run(f) {
if (this.running < this.poolSize) {
this.running++;
return (0, result_1.thenF)(f, x => {
this.running--;
this.check();
return x;
}, _e => {
this.running--;
this.check();
});
}
return this.queue(f);
}
queue(f) {
return new Promise((resolve, reject) => {
this.fs.push(() => {
this.running++;
return (0, result_1.thenF)(f, x => {
this.running--;
resolve(x);
this.check();
return x;
}, e => {
this.running--;
reject(e);
this.check();
});
});
});
}
check() {
if (this.fs.length > 0 && this.running < this.poolSize) {
const f = this.fs.dequeue();
try {
f();
}
catch (e) {
if (this.logError) {
console.error(e);
}
}
}
}
}
exports.NonVoidResultPool = NonVoidResultPool;