typed-utilities
Version:
Strongly typed general purpose utilities
53 lines (43 loc) • 873 B
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AsyncSemaphore = void 0;
class AsyncSemaphore {
constructor(max) {
this.max = max;
this._current = 0;
this.queue = [];
}
run = async fn => {
this._current++;
try {
return await fn();
} finally {
this._current--;
this.trigger();
}
};
trigger = () => {
const next = this.queue.pop();
if (next) {
next();
}
};
use = async fn => {
if (this._current < this.max) {
return await this.run(fn);
}
return await new Promise(resolve => {
this.queue.push(resolve);
}).then(() => this.run(fn));
};
get current() {
return this._current;
}
get length() {
return this.queue.length;
}
}
exports.AsyncSemaphore = AsyncSemaphore;
//# sourceMappingURL=AsyncSemaphore.js.map