I actually recommend to do a factory or service that watching if you have active request and you waiting for it.
yourApp.factory('apiReqeust', ['$http', function($http) {
// If you want to complete all requests that you sending,
// make this varable an empty array and push every new request inside it.
var waitingRequest = null; // Or quenuedRequests = [];
var isWorking = false;
// In my case I will not make an array, and will have only one request that will wait.
// I mean the last attempted request.
// This is perfect for an Autocomplete API
function request(options, callback) {
if (isWorking) {
// If you are already running request at this time.
// Replace waiting request with this one. (this one is newer request)
waitingRequest = {options: options, callback: callback}
// EDIT! I forgot about the return statement.
// You need to stop, otherwise the request will be executed anyway.
return;
}
isWorking = true;
$http(options).success(function(data) {
// When the request ends, tell that you are not working
// So you can execute next request immediately
isWorking = false;
// execute callback with data parameter.
callback(data);
// If you have waiting request yet. execute it.
if (waitingRequest) {
request(waitingRequest.options, waitingRequest.callback);
waitingRequest = null;
}
}).error(function(err) {
isWorking = false;
callback(null, err);
if (waitingRequest) {
request(waitingRequest.options, waitingRequest.callback);
}
});
}
return request;
});
The usage of this is:
// Factory or controller or whatever that can depend on above factory
youApp.factory('another-whatever', ['apiRequest', function(apiRequest) {
options = {'Some': 'HttpOptions'};
apiRequest(options, function(data, err) {
if (err) throw new Error(err);
// And here you doing what you want with the data.
});
}]);
I am not tested this code. I don't know if it's working. But I hope you got the idea.