advanced_waitgroup_js
Version:
## Installation
100 lines (99 loc) • 3.26 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
var WaitGroup = /** @class */ (function () {
function WaitGroup() {
this.waiting = false;
this._counters = [];
}
WaitGroup.prototype.add = function (counter) {
var _this = this;
if (this.waiting) {
throw new Error("Can't call `add` if there's an `wait` call waiting resolution");
}
if (!counter) {
counter = 1;
}
var _loop_1 = function (i) {
var resolve;
var reject;
var promise = new Promise(function (res, rej) {
resolve = res;
reject = rej;
_this._counters.push({
promise: promise,
resolve: resolve,
reject: reject,
});
});
};
for (var i = 0; i < counter; i++) {
_loop_1(i);
}
};
WaitGroup.prototype.done = function (err) {
if (!this.waiting) {
throw new Error("Can't call `done` before `wait`");
}
var counter = this._counters.splice(0, 1)[0];
if (!counter) {
throw new Error("Can't call `done` when there are no counters");
}
if (err) {
return counter.reject(err);
}
counter.resolve();
};
WaitGroup.prototype.wait = function (timeout, ttl, onOver) {
var _this = this;
var bodyFunction = function (resolve, reject) {
if (_this.waiting) {
throw new Error("There's already an `wait` call waiting resolution");
}
if (_this._counters.length === 0) {
throw new Error("Can't call `wait` when there are no counters");
}
var timeoutId;
if (timeout) {
timeoutId = setTimeout(function () {
_this._counters.forEach(function (counter) {
counter.reject('canceled');
});
reject(new Error('Timeout reached'));
}, timeout);
}
_this.waiting = true;
Promise.all(_this._counters.map(function (counter) { return counter.promise; }))
.then(function () {
return resolve();
})
.catch(function (err) {
return reject(err);
})
.finally(function () {
clearTimeout(timeoutId);
_this.waiting = false;
});
};
var promise = new Promise(bodyFunction);
if (ttl) {
var handler = function () {
_this.ultimatum('race-lose');
if (onOver) {
onOver();
}
};
return Promise.race([promise, setTimeout(handler, ttl)]);
}
else {
return promise;
}
};
WaitGroup.prototype.ultimatum = function (error) {
var length = this._counters.length;
for (var i = 0; i < length && this.waiting; i++) {
this.done(error);
}
};
return WaitGroup;
}());
exports.default = WaitGroup;
;