Skip to content

Instantly share code, notes, and snippets.

@wehrhaus
Created May 25, 2018 15:46
Show Gist options
  • Save wehrhaus/22adf09da3602aaf2c13307dace8f4de to your computer and use it in GitHub Desktop.
Save wehrhaus/22adf09da3602aaf2c13307dace8f4de to your computer and use it in GitHub Desktop.
Request Pool using Angular
'use strict';
import BaseCollection from './data/collections/BaseCollection';
import * as _ from 'lodash';
RequestPool.$inject = ['$q'];
export default function RequestPool($q) {
function RequestPool(cap) {
this.cap = cap;
this.openRequests = 0;
this.openPool = new BaseCollection();
this.queuePool = new BaseCollection();
}
RequestPool.prototype = {
cap: 6,
openRequests: 0,
openPool: null,
queuePool: null,
poolRequest: function() {
var deferred = $q.defer();
var _id = _.uniqueId();
var requestObject = {
id: _id,
deferred: deferred
};
if (this.openPool.length >= this.cap) {
this.queuePool.add(requestObject);
} else {
this.openPool.add(requestObject);
deferred.resolve(requestObject);
}
return deferred.promise;
},
dequeueRequest: function(id) {
this.openPool.remove(id);
if (this.queuePool.length > 0 &&
this.openPool.length < this.cap) {
var requestObject = this.queuePool.first();
this.queuePool.remove(requestObject.id);
this.openPool.add(requestObject);
requestObject.deferred.resolve(requestObject);
}
},
close: function() {
this.queuePool.each(function(poolObject) {
poolObject.deferred.reject();
});
this.queuePool.empty();
}
};
return RequestPool;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment