ilorest
Version:
iLO REST JavaScript Library
109 lines (95 loc) • 3.82 kB
JavaScript
;
/*
* (c) Copyright 2018 Hewlett Packard Enterprise Development LP
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations
* under the License.
*/
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var promise = require('bluebird');
var throttle = (function () {
function throttle(MAX) {
_classCallCheck(this, throttle);
typeof MAX === 'number' && MAX > 0 ? this.MAX = MAX : this.MAX = 1;
this.queue = [];
this.count = 0;
}
_createClass(throttle, [{
key: '_deferObj',
value: function _deferObj(callback) {
var _value = callback;
var _resolve, _reject;
var _promise = new promise(function (resolve, reject) {
_resolve = resolve;
_reject = reject;
});
return {
getPromise: function getPromise() {
return _promise;
},
start: function start() {
_resolve(_value);
return _promise;
},
cancel: function cancel() {
_reject(_value);
return _promise;
}
};
}
}, {
key: '_throttling',
value: function _throttling(deferal) {
this.queue.push(deferal);
while (this.count < this.MAX) {
var obj = this.queue.shift();
if (obj) {
this.count += 1;
obj.start();
} else {
break;
}
}
}
}, {
key: '_startNext',
value: function _startNext() {
this.count -= 1;
var obj = this.queue.shift();
if (obj) {
this.count += 1;
obj.start();
}
}
}, {
key: 'run',
value: function run(callback) {
var _this = this;
var deferal = this._deferObj(callback);
var originalPromise = {};
this._throttling(deferal);
return deferal.getPromise().then(function (callback) {
originalPromise = callback();
return originalPromise;
}).then(function () {
_this._startNext();
return originalPromise;
})['catch'](function (err) {
_this._startNext();
throw err;
});
}
}]);
return throttle;
})();
exports.throttle = throttle;