Skip to content

Instantly share code, notes, and snippets.

@sebastieno
Created March 27, 2016 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastieno/fb5d305f89acd0faec8a to your computer and use it in GitHub Desktop.
Save sebastieno/fb5d305f89acd0faec8a to your computer and use it in GitHub Desktop.
Http request locker for AngularJS
var IS;
(function (IS) {
var HttpRequestLocker = (function () {
function HttpRequestLocker($http, $q, requestConfig, successCallback) {
this.$http = $http;
this.$q = $q;
this.requestConfig = requestConfig;
this.successCallback = successCallback;
}
HttpRequestLocker.prototype.execute = function () {
var _this = this;
var deferred = this.$q.defer();
if (!this.waitingDeferred || this.waitingDeferred.length === 0) {
this.waitingDeferred = [];
this.$http(this.requestConfig).success(function (result) {
if (_this.successCallback) {
result = _this.successCallback(result);
}
for (var i = 0; i < _this.waitingDeferred.length; i++) {
_this.waitingDeferred[i].resolve(result);
}
}).error(function (error) {
for (var i = 0; i < _this.waitingDeferred.length; i++) {
_this.waitingDeferred[i].reject(error);
}
}).finally(function () {
_this.waitingDeferred = null;
});
}
this.waitingDeferred.push(deferred);
return deferred.promise;
};
return HttpRequestLocker;
})();
IS.HttpRequestLocker = HttpRequestLocker;
})(IS || (IS = {}));
module IS {
export class HttpRequestLocker {
constructor(private $http: ng.IHttpService,
private $q: ng.IQService,
private requestConfig: ng.IRequestConfig,
private successCallback?: (data : any) => any) {
}
private waitingDeferred: ng.IDeferred<any>[];
execute(): ng.IPromise<any> {
var deferred = this.$q.defer();
if (!this.waitingDeferred || this.waitingDeferred.length === 0) {
this.waitingDeferred = [];
this.$http(this.requestConfig).success((result) => {
if (this.successCallback) {
result = this.successCallback(result);
}
for (var i = 0; i < this.waitingDeferred.length; i++) {
this.waitingDeferred[i].resolve(result);
}
}).error((error) => {
for (var i = 0; i < this.waitingDeferred.length; i++) {
this.waitingDeferred[i].reject(error);
}
}).finally(() => {
this.waitingDeferred = null;
});
}
this.waitingDeferred.push(deferred);
return deferred.promise;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment