@beenotung/tslib
Version:
utils library in Typescript
95 lines • 2.68 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 {
constructor(poolSize) {
this.poolSize = poolSize;
this.fs = new ring_buffer_1.RingBuffer(array_1.getMaxArraySize());
this.running = 0;
}
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();
}
result_1.then(x, () => {
this.running--;
this.next();
});
}
}
}
exports.VoidResultPool = VoidResultPool;
class NonVoidResultPool {
constructor(poolSize, logError = true) {
this.poolSize = poolSize;
this.logError = logError;
this.fs = new ring_buffer_1.RingBuffer(array_1.getMaxArraySize());
this.running = 0;
}
/**
* @description error will be ignored
* */
run(f) {
if (this.running < this.poolSize) {
this.running++;
return 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 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;
//# sourceMappingURL=result-pool.js.map