node-worker-threads-pool-ts
Version:
Simple worker threads pool using Node's worker_threads module. Compatible with ES6+ Promise, Typescript, Async/Await.
42 lines • 1.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PromiseWithTimer = exports.isTimeoutError = void 0;
class TimeoutError extends Error {
constructor(message) {
super(message);
this.name = "TimeoutError";
}
}
/**
* Detect if error is a Timeout error.
*/
function isTimeoutError(err) {
return err instanceof TimeoutError;
}
exports.isTimeoutError = isTimeoutError;
class PromiseWithTimer {
constructor(p, timeout) {
this.p = p;
this.timeout = timeout;
this.timeoutSymbol = Symbol("timeoutSymbol");
}
_createTimer() {
return new Promise((resolve) => {
this.timerID = setTimeout(resolve, this.timeout, this.timeoutSymbol);
});
}
async startRace() {
if (this.timeout <= 0) {
return await this.p;
}
const result = await Promise.race([this.p, this._createTimer()]);
if (result === this.timeoutSymbol) {
throw new TimeoutError("timeout");
}
if (this.timerID)
clearTimeout(this.timerID);
return result;
}
}
exports.PromiseWithTimer = PromiseWithTimer;
//# sourceMappingURL=promise-with-timer.js.map