Created
June 6, 2013 21:52
-
-
Save louiszuckerman/5725311 to your computer and use it in GitHub Desktop.
Queue to manage ajax requests (made for angularjs $resource objects)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Example usage: | |
ajaxEnqueue(Resource.get, {id: 1}, function(val) {console.log("API returned "+val)"}) | |
Where Resource is an angular $resource object. | |
This queue will throttle AJAX requests so that only a limited number (ajaxParallel) are in flight at a time. | |
*/ | |
//TODO: Encapsulate this in a service object, get rid of globals. | |
var ajaxQueue = []; | |
var ajaxParallel = 10; | |
var ajaxOutstanding = 0; | |
function ajaxEnqueue(method, params, success, failure) { | |
ajaxQueue.push(function() { | |
method(params, function(val) { | |
if (typeof(success) == "function") { | |
success(val); | |
} | |
ajaxOutstanding--; | |
ajaxDequeue(); | |
}, function(val) { | |
if (typeof(failure) == "function") { | |
failure(val); | |
} | |
ajaxOutstanding--; | |
ajaxDequeue(); | |
}); | |
}); | |
ajaxDequeue(); | |
} | |
function ajaxDequeue() { | |
if (ajaxOutstanding < ajaxParallel && ajaxQueue.length > 0) { | |
ajaxOutstanding++; | |
ajaxQueue.shift()(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment