Skip to content

Instantly share code, notes, and snippets.

@SudoPlz

SudoPlz/HoldList.js

Created Jan 3, 2018
Embed
What would you like to do?
import _ from 'underscore';
export default class HoldList {
constructor() {
this.holdList = [];
this.runningRequestCnt = 0;
}
invokeAll(err, exclude) {
if (this.holdList && this.holdList.length > 0) {
for (const unresolvedObj of this.holdList) {
if (unresolvedObj) {
const {
resolve,
reject,
path,
// timestampStarted,
} = unresolvedObj;
if (err && reject) {
// console.log(`request: ${path} waited for ${
// round(now() - timestampStarted, 1)}ms and got rejected`);
reject(err);
} else if (err == null && resolve) {
if (exclude && path === exclude) {
// console.log(`request: ${path} waited for ${
// round(now() - timestampStarted, 1)}ms and then got RESOLVED`);
resolve(false);
} else {
resolve(true);
}
}
}
}
this.holdList = [];
}
}
createUnresolvedPromise(path, timestampStarted) {
const self = this;
return new Promise((resolve, reject) => {
if (self.holdList == null) {
self.holdList = [];
}
self.holdList.push({
resolve,
reject,
path,
timestampStarted,
});
});
}
removePromise(promise) {
if (this.holdList && this.holdList.length > 0) {
// remove it's reference from the Req Promise array
this.holdList = _.reject(this.holdList,
curPromise => curPromise === promise,
);
}
}
getWaitingRequestCnt() {
return this.holdList && this.holdList.length;
}
increaseRunningRequestCnter() {
this.runningRequestCnt += 1;
}
decreaseRunningRequestCnter() {
if (this.runningRequestCnt > 0) {
this.runningRequestCnt -= 1;
if (this.runningRequestCnt === 0) {
this.invokeAll();
}
}
}
getRunningRequestCnt() {
return this.runningRequestCnt;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment